Hashes in Perl aren't really that hard to understand; they're not that much harder than understanding how a phone book works. This article introduces you to hashes, what they do, and how to use them. It is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
Just like scalar variables have a $prefix, and arrays have a@prefix, hashes have their own prefix—a percent sign. Again, the same naming rules apply, and the variables%hash,$hash, and@hashare all different.
One way of creating a hash variable is to assign it a list that is treated as a collection of key/value pairs:
In this case, the hash could be saying that “Gary’s whereabouts is Dallas,” “Lucy lives in Exeter,” and so on. All it really does is pair Gary and Dallas, Lucy and Exeter, and so on. How the pairing is interpreted is up to you.
If we want to make the relationship, and the fact that we’re dealing with a hash, a little clearer, we can use the=>operator. That’s not>=, which is greater-than-or-equal-to; the=>operator acts like a “quoting comma.” That is, it’s a comma, but whatever appears on the left-hand side of it—and only the left—is treated as a double-quoted string.
%where = ( Gary => "Dallas", Lucy => "Exeter", Ian => "Reading", Samantha => "Oregon" );
The scalars on the left of the arrow are called the hash keys, the scalars on the right are the values. We use the keys to look up the values.
Note Hash keys must be unique. You cannot have more than one entry for the same name, and if you try to add a new entry with the same key as an existing entry, the old one will be overwritten. Hash values meanwhile need not be unique.
Key uniqueness is more of an advantage than a limitation. Every time the word “unique” comes into a problem, like counting the unique elements of an array, your mind should immediately echo “Use a hash!”
Because hashes and arrays are both built from structures that look like lists, you can convert between them, from array to hash, like this:
Assigning an array to a hash will work properly only when there are an even number of elements in the array.
The hash can then be assigned back to an array like so:
@array = %where;
However, you need to be careful when converting back from a hash to an array. Hashes do not have a guaranteed order; although values will always follow keys, you cannot tell what order the keys will come in. Since hash keys are unique, however, we can be sure that%hash1 = %hash2is guaranteed to copy a hash accurately.