Perl Programming/Hash variables

Previous: Array variables Index Next: References and data structures

A Perl hash is similar to an ordinary array, but instead of using integer indexes, a hash uses "keys" that can take on any scalar value. These are usually strings or numbers.

Syntax: instead of the @ operator, associative arrays use the % symbol, and rather than square brackets [], as in $myarray[0], hash elements are referenced using curly brackets {}, as in $myhash{"george"}.

Hashes are one of the most powerful and commonly used features in Perl. A typical use would be to build a hash that contains a "dictionary", with each key being a word in the dictionary, and the corresponding values being the definitions of those words.

A hash containing the sounds various household pets make is below

my %petsounds = ("cat" => "meow",
                 "dog" => "woof",
                 "snake" => "hiss");

'=>' and ',' are actually interchangeable, so the right side could look exactly like an array. This means that you can assign an array to a hash. In such an assignment, each element with an even index (starting from 0) in the array becomes a key in the hash. The following statements create the same hash as the previous one does

my @array = ("cat", "meow", "dog", "woof", "snake", "hiss");
my %petsounds = @array;

But the first style is more preferred because it makes the statement more readable.

To access a hash element, use the curly brackets:

 print STDOUT "The cat goes " . $petsounds{"cat"} . ".\n";

will print the following to STDOUT

The cat goes meow.

To add a new sound item to a hash

$petsounds{"mouse"} = "squeak!";

To overwrite an existing element, just reassign it

$petsounds{"dog"} = "arf!";  # The dog now goes "arf!"

To remove an item from a hash, use delete. Setting the value to undef does not delete the item; using exists on a key that has been set to undef will still return true.

delete($petsounds{"cat"});  # will remove "cat" from our hash

"Associative Arrays"


Originally, a "hash" was called an "associative array", but this term is a bit outdated (people just got sick and tired of using seven syllables). Although it isn't intuitive for newcomers to programming, "hash" is now the preferred term. The name is derived from the computer science term, hashtable.

Working with hashes


Printing hash contents


If you know PHP, you may have thought by now of some convenient way to print the contents of your array the way print_r does...

use Data::Dumper;

print Dumper(\%hash);

Counting the number of entries in a hash


To get the size of the hash, simply find the size of the result of the keys function, by evaluating it in scalar context:

my %hash = (
   'key1' => 1,
   'key2' => 2

print "Hash has " . keys(%hash) . " elements\n";
my $num_elements = scalar(keys(%hash));

Hash of Hashes of Hashes


You can define multidimensional hash array variables. An example may look like this:


use Data::Dumper;

my %a=();


foreach my $k1 ( sort keys %a ) {
  foreach my $k2 ( sort keys %{$a{$k1}} ) {
    foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) {
      print "$k1\t$k2\t$k3\t$a{$k1}{$k2}{$k3}\n";

print Dumper(\%a);

This code will produce:

 1       a       A       FIRST
 1       b       C       SECOND
 1       c       B       THIRD
 $VAR1 = {
           '1' => {
                    'c' => {
                             'B' => 'THIRD'
                    'a' => {
                             'A' => 'FIRST'
                    'b' => {
                             'C' => 'SECOND'

Previous: Array variables Index Next: References and data structures