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.
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, ... ); |
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".
You can also create elements in a hash on the fly:
my %monthdays = (); $monthdays{"January"} = 31; $monthdays{"February"} = 28; ... |
Hashes have no internal order
There is no equivalent to $#array to get the size of a hash
However, there are functions such as each(), keys() and values() which will help you manipulate hash data. We look at these later, when we deal with functions.
You may like to look up the following functions which related to hashes: keys(), values(), each(), delete(), exists(), and defined().
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.
Create a hash of people and something interesting about them
Print out a given person's interesting fact
Change an person's interesting fact
Add a new person to the hash
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