$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 pianoAs usual, the keys are not stored in the order they are entered, nor are they sorted in any predictable fashion.