Perl Hash

Perl Hash is a logically discontinuous data structure (meaning the first item referred to the hash is not necessarily the first item that you input). It can be defined like the following:

my %hash = qw ( name Ingram age 22 );

The odd number of scalars defined the keys to be stored, and the even number of scalars will be the values for the key. This means that to define a hash, you need to have an even number of scalars pass as the qw() parameters. However, there is a more readable way to define a hash, shown below:

my %hash = ( name=>Ingram, age=>22 );

Or with #Perl Reference using curly braces {}:

my $hashRef = { name=>Ingram, age=>22 };

Note: Be aware that Hash will be treated as list in other contexts such as Perl Array. Since there is no association between keys and values in a list, passing a Hash to an array will destroy the established relationship. One of the solution is to use #Perl Reference.

To get the value of the key from the hash, using the “$” sigil and the following syntax. However if the key hasn’t been created before this, undef# will be returned.

my $name = $hash{name}

Other than keys and values, Perl Hash stores a special variable called iterator that could be used by the each() to return a pair of key and value and then advance to the next pair. The function will return an empty list when it encountered no pair left after the current pair, which is recognised by the Perl Boolean# as false. Its usage could be as simple as iterating through the hash using a while loop, such as the following:

while(my($key, $value)=each(%hash)) {
  print "key='$key', value='$value'\n";
}

Note: We could reset the iterator by calling the function keys() on the Perl Hash.

We can also test whether the key specified exists in the Perl Hash using the function exist(). However, keep in mind that it doesn’t work well with multi-level hash verification, that is there is a hash table contained in another hash table. Perl will autovivify# all the lower-level keys and will not check the validity of the higher-level key. Therefore, it is recommended to test the key individually, level by level, from high to low, in order to prevent such bug from happening.

Links to this page
#perl #hash-table