Hashes

A hash is a two-dimensional array which contains keys and values. Instead of looking up items in a hash by an array index, you can look up values by their keys.

Hashes are covered in the Camel on pages 7-8, then in more detail on page 50 or in perldoc perldata.

Initialising a hash

Hashes are initalised in exactly the same way as arrays, with a comma separated list of values:

my %monthdays = ("January", 31, "February", 28, "March", 31, ...);

Of course, there's more than one way to do it:

my %monthdays = (
        "January"       =>      31,
        "February"      =>      28,
        "March"         =>      31,
        ...
);

The spacing in the above example is commonly used to make hash assignments more readable.

The => operator is syntactically the same as the comma, but is used to distinguish hashes more easily from normal arrays. Also, you don't need to put quotes on the item which comes immediately before the => operator:

my %monthdays = (
        January       =>      31,
        February      =>      28,
        March         =>      31,
        ...
);

Reading hash values

You get at elements in a hash by using the following syntax:

print $monthdays{"January"};    # prints 31

Again you'll notice the use of the dollar sign, which you should read as "the monthdays belonging to January".

Adding new hash elements

You can also create elements in a hash on the fly:

my %monthdays = ();
$monthdays{"January"} = 31;
$monthdays{"February"} = 28;
...

Other things about hashes

You may like to look up the following functions which related to hashes: keys(), values(), each(), delete(), exists(), and defined().

What's the difference between a hash and an associative array?

Back in the days of Perl version 4 (and earlier), hashes were called associative arrays. The name "hash" is now preferred because it's much quicker to type. If you consider all the times that hashes are talked about in the newsgroup comp.lang.perl.misc and other Perl newsgroups, the renaming of associative arrays to hashes has resulted in a major saving of bandwidth.

Exercises

  1. Create a hash of people and something interesting about them

  2. Print out a given person's interesting fact

  3. Change an person's interesting fact

  4. Add a new person to the hash

  5. What happens if you try to print an entry for a person who's not in the hash?

Answers to these exercises are given in exercises/answers/hash.pl