Copyright © tutorialspoint.com

# PERL Hash Variable

Hashes are an advanced form of array. One of the limitations of an array is that the information contained within it can be difficult to get to. For example, imagine that you have a list of people and their ages. The hash solves this problem very neatly by allowing us to access that @ages array not by an index, but by a scalar key. For example to use age of different people we can use thier names as key to define a hash.

    %ages = ('Martin' => 28,
             'Sharon' => 35,
             'Rikke' => 29,);

    print "Rikke is $ages{Rikke} years old\n";

    This will produce following result
    Rikke is 29 years old

# Creation of Hash

Hashes are created in one of two ways. In the first, you assign a value to a named key on a one-by-one basis:

    $ages{Martin} = 28;

In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example,

    %hash = ('Fred' , 'Flintstone', 'Barney', 'Rubble');

For clarity, you can use => as an alias for , to indicate the key/value pairs:

    %hash = ('Fred' => 'Flintstone',
             'Barney' => 'Rubble');

# Extracting Individual Elements

You can extract individual elements from a hash by specifying the key for the value that you want within braces:

    print $hash{Fred};

    This will print following result
    Flintstone

# Extracting Slices

You can extract slices out of a hash just as you can extract slices from an array. You do, however, need to use the @ prefix because the return value will be a list of corresponding values:

    #!/uer/bin/perl

    %hash = (-Fred => 'Flintstone', -Barney => 'Rubble');
    print join("\n",@hash{-Fred,-Barney});

    This will produce following result
    Flintstone
    Rubble

Note: Using $hash{-Fred, -Barney} would return nothing.

# Extracting Keys and Values

You can get a list of all of the keys from a hash by using keys

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
    print "The following are in the DB: ",join(', ',values %ages),"\n";

    This will produce following result
    The following are in the DB: 29, 28, 35

These can be useful in loops when you want to print all of the contents of a hash:

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
    foreach $key (%ages)
    {
      print "$key is $ages{$key} years  old\n";
    }

    This will produce following result
    Rikke is 29 years  old
    29 is  years  old
    Martin is 28 years  old
    28 is  years  old
    Sharon is 35 years  old
    35 is  years  old

The problem with this approach is that (%ages) returns a list of values. So to resolve this problem we have each function which will retun us key and value pair as given below

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
    while (($key, $value) = each %ages)
    {
      print "$key is $ages{$key} years old\n";
    }

    This will produce following result
    Rikke is 29 years old
    Martin is 28 years old
    Sharon is 35 years old

# Checking for Existence

If you try to access a key/value pair from a hash that doesn.t exist, you.ll normally get the undefined value, and if you have warnings switched on, then you.ll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be:

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
    if (exists($ages{"mohammad"}))
    {
      print "mohammad if $ages{$name} years old\n";
    }
    else
    {
      print "I don't know the age of mohammad\n";
    }

    This will produce following result
    I don't know the age of mohammad

# Sorting/Ordering Hashes

There is no way to simply guarantee that the order in which a list of keys, values, or key/value pairs will always be the same. In fact, it's best not even to rely on the order between two sequential evaluations:

    #!/usr/bin/perl

    print(join(', ',keys %hash),"\n");
    print(join(', ',keys %hash),"\n");

If you want to guarantee the order, use sort, as, for example:

      print(join(', ',sort keys %hash),"\n");

If you are accessing a hash a number of times and want to use the same order, consider creating a single array to hold the sorted sequence, and then use the array (which will remain in sorted order) to iterate over the hash. For example:

    my @sortorder = sort keys %hash;
    foreach my $key (@sortorder)

# Hash Size

You get the size - that is, the number of elements - from a hash by using scalar context on either keys or values:

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
    print "Hash size: ",scalar keys %ages,"\n";

    This will produce following result
    Hash size: 3

# Add & Remove Elements in Hashes

Adding a new key/value pair can be done with one line of code using simple assignment operator. But to remove an element from the hash you need to use delete function.

    #!/usr/bin/perl

    %ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);

    # Add one more element in the hash
    $age{'John'} = 40;
    # Remove one element from the hash
    delete( $age{'Sharon'} );

Copyright © tutorialspoint.com