HashesIn most languages there are arrays. Another very useful data structure which is not often found is called a hash or an associative array. The language "awk" on Unix may have been the first to use them.In Java there is the concept of a hash as well but it is not built-in, not an integral part of the language like it is in Perl so the syntax is more verbose and cumbersome. Hashes are like arrays but the index (also called a key) can be an arbitrary string (or scalar) instead of an integer. Arrays are ordered collections; hashes are not. To indicate that a variable contains a hash you use the percent '%' instead of the at sign '@'. They are initialized with pairs of scalars:
They are referenced just like arrays except that you use
braces { } rather than brackets [ ]:
One way to think of hashes is that instead
of asking for the 3rd element of an array
you now can ask for the Bill'th element of a hash :).
If you assign to an existing hash element it will overwrite the contents (just like arrays). Syntactic Sugar for HashesPerl offers this syntactic sugar: the string used as the key does not need to be quoted if it contains only word type characters:
And syntactic sugar for the initialization of a hash.
Instead of:
You can say:
This makes it clear that the data comes in pairs.
A side effect of the => (which is very much
like a comma and can be used where ever a comma is used)
is that the word to its left is automatically quoted.
It cannot contain any blanks or punctuation.
KeysTo get a list of all the indices that you can validly use there is the function "keys" which returns an array.or@names = keys %age;
Note that the keys array is not in any particular order.
If you want a certain order - sort it!
or within a for statement:@names = sort keys %age;
Does a Key Exist?To see if a string can be used as an key there is the function 'exists':
Note that there may be an entry in a hash
for a given string but its value may be undefined.
This IS a valid value and the entry DOES exist.
Because of this it is best to check for existence
rather than definedness or for truth (because
0 or the empty string IS a valid value!).
If you access a hash with an invalid key you will get the undefined (and false) value undef. Hash InterpolationHash elements can be interpolated into a double quoted string but not the hash as a whole (unlike arrays).
When to use a Hash?Hashes are very useful when you need to make a lookup table or for finding all the unique elements of a set. This happens much more frequently than you might realize! Hashes prove to be a very useful part of the language.Exercises
|