Perl Variables  «Prev  Next»
Lesson 14Perl Hash indexes
ObjectiveAccess a hash variable.

Perl Hash Indexes

In this lesson you will learn how to access the elements of a hash. In the process, we will use this hash with all the Academy Award Best Picture winners from 1980 to 1997:

%bestpix = ( 
   1980 => "Ordinary People", 
   1981 => "Chariots of Fire", 
   1982 => "Gandhi",
   1983 => "Terms of Endearment", 
   1984 => "Amadeus", 
   1985 => "Out of Africa", 
   1986 => "Platoon",
   1987 => "The Last Emperor", 
   1988 => "Rain Man", 
   1989 => "Driving Miss Daisy",
   1990 => "Dances with Wolves", 
   1991 => "The Silence of the Lambs",
   1992 => "Unforgiven", 
   1993 => "Schindler's List", 
   1994 => "Forrest Gump",
   1995 => "Braveheart",
   1996 => "The English Patient",
   1997 => "Titanic",
   );

The simplest way to access a hash value is with this syntax:
$hash{key}
As in the case of the array, the value is a scalar, so you use the $ character to access it. The curly brackets ({ and }) are used to indicate the key, and in Perl 5 they effectively quote the string so you don't need to use quotation marks.
For instance, if you wanted to see just the best picture for 1993, you could use this:

Beginning Perl Programming
print "$bestpix{1993}\n";
 # Schindler's List

Or if you wanted to print all the records in the order of the key, you could do this:
foreach $year (sort keys %bestpix) { 
  print "$year: $bestpix{$year}\n"; 
}

You will learn the details of the foreach loop and the sort function later in the course, but this is perhaps the most common way to access a hash, so it's worth the time for you to understand it now. Here is an explanation of this particular usage.

The foreach Loop
A foreach loop takes two arguments, a scalar and a list. The loop is run once for each element in the list, and the scalar (here, $year) is used to hold the current element. The keys operator returns a list of keys from the hash, and the sort operator sorts that list. So in this case, the list of keys from the hash is sorted and used to iterate the foreach loop.

Hash Index Exercise

Click the Exercise link below to create a hash and print the entries.
Hash Index Exercise