eWebProgrammer eweb  






Advanced Perl  «Prev  Next»
Lesson 15 Perl hashes
Objective Learn how to initialize and access data in a hash.

Perl Hashes

Arrays are useful for storing two-dimensional data, but what if you want to associate each element of the array with some other data?
For this situation you would use a hash.
Perl hash
A hash is like an array that is indexed with scalar strings instead of ordered numbers.
A hash is distinguished by the initial % (percent sign), like this: %viceprez.
You can initialize a hash like this:
%viceprez= (
   'Franklin' => 'Henry A. Wallace',
   'Harry'    => 'Alben W. Barkley',
   'Dwight'   => 'Richard M. Nixon',
   'John'     => 'Lyndon B. Johnson', 
   'Lyndon'   => 'Hubert H. Humphrey',
   'Richard'  => 'Spiro T. Agnew',
   'Gerald'   => 'Nelson A. Rockefeller',
   'Jimmy'    => 'Walter F. Mondale',
   'Ronald'   => 'George H. Bush',
   'George'   => 'J. Dan Quayle',
   'Bill'     => 'Al Gore, Jr.',
   );


(I know that some of these presidents had more than one vice president, but we need more-complex data structures to deal with that.
Stay tuned for the next lesson, and, if nothing else, you'll get some more American history.)

Accessing the hash in Perl

Each entry in a hash has two elements, the key and the value. The first element in the entry is the key, and the second element is the value.
The keys are used to access the hash entries much as the ordered index is used to access an array element.
hash diagram
hash diagram
You can access the value of one of the hash's elements like this:
$viceprez{'Harry'} # Alben W. Barkley
In this case, the element in the braces is the key ("Harry"),
and the result is the value ("Alben W. Barkley").
Of course, you can also use this form within a string:


print "$viceprez{'Harry'}\n" # Alben W. Barkley
You may use the same syntax to add elements to the hash:
$viceprez{'Herbert'} = 'Charles Curtis';
If you want a list of all the keys, you can do this:
keys   %viceprez    # presidents
If you want a list of all the values, you can do this:
values %viceprez # vp's

Perl hash records

Keep in mind that records in the hash are stored in no particular order (they actually work faster that way), so the lists that you get from keys and values will not be in the same order as the hash was defined.