Hashes in Perl aren't really that hard to understand; they're not that much harder than understanding how a phone book works. This article introduces you to hashes, what they do, and how to use them. It is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
To look up a value in a hash, we use something similar to the index notation for arrays. However, instead of locating elements by number, we’re now locating them by name, and instead of using square brackets, we use curly braces.
Here’s a simple example of looking up details in a hash:
#!/usr/bin/perl -w # hash.pl
use strict;
my $who = "Ian";
my %where = ( Gary => "Dallas", Lucy => "Exeter", Ian => "Reading", Samantha => "Oregon" );
print "Gary lives in ", $where{Gary}, "\n"; print "$who lives in $where{$who}\n";
$ perl hash.pl Gary lives in Dallas Ian lives in Reading $
The first thing we do in this program is set up our main hash, which tells us where people live.
my %where = ( Gary => "Dallas", Lucy => "Exeter", Ian => "Reading", Samantha => "Oregon" );
Like scalars and arrays, hash variables must be declared withmy()when using strict.
Now we can look up an entry in our hashes—we’ll ask “Where does Gary live?”
print "Gary lives in ", $where{Gary}, "\n";
This is almost identical to looking up an array element, except for using curly braces instead of square brackets and the fact that we are now allowed to use strings to index our elements. Notice that the keyGaryis not quoted within the curly braces. If the key contains no whitespace characters, it is assumed quoted within the curly braces. If the key does contain whitespace characters, then we will have to quote it.
The next line is
print "$who lives in $where{$who}\n";
Just as with array elements, we need not use a literal to index the element—we can look up using a variable as well.