next up previous contents
Next: Functions for Working with Up: Hashes Previous: What is a hash?   Contents


Hashes and Lists

In many situations, a hash can be thought of as a list, with the hash's keys alternating with it's corresponding values. One place where this is very useful is in initializing a hash; you can simply provide a list of keys alternating with their values. For example, suppose we wish to create a hash call %instrument, containing the instruments of various jazz musicians. One way is to define each element of the hash as a separate statement:
     $instrument{miles} = 'trumpet';
     $instrument{monk}  = 'piano';
     $instrument{dizzy} = 'trumpet';
     $instrument{coltrane} = 'sax';
It would usually be easier to do the assignment in a single statement with a list:
    %instrument = ('miles','trumpet','monk','piano',
                   'dizzy','trumpet','coltrane','sax');
Note that, because of the special handling of barewords in hash indices, it was safe to leave off the quotes when the elements of the hash were assigned individually (since they contain no blanks or special characters). To allow the same freedom when initializing a hash from a list, and to make it a little clearer which value belongs to which key, perl provides an alternative syntax for this special case. Instead of separating values from their respective keys with a comma (,), you can use the ``arrow'' operator: =>. The only real difference between the comma and the arrow operator in this context is that barewords to the left of the arrow operator will be treated the same way as indices to a hash are treated (Section 6.1). Our example could use the arrow operator as follows:
     %instrument = (miles=>'trumpet',monk=>'piano',
                    dizzy=>'trumpet',coltrane=>'sax');
Note that values to the right of the arrow operator are treated exactly as they would be in a comma-separated list; it's only the keys (on the left of the arrow operator) which are given special treatment.

Perhaps the easiest way to see the relationship between an array and a hash is to assign a hash to array -- the result is an array whose elements alternate between the keys of the hash, and the corresponding values:

@in = %instrument;
print join(" ",@in)."\n";
   #results in coltrane sax dizzy trumpet miles trumpet monk piano
As usual, the keys are not stored in the order they are entered, nor are they sorted in any predictable fashion.


next up previous contents
Next: Functions for Working with Up: Hashes Previous: What is a hash?   Contents
Phil Spector 2002-10-18