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).
We have talked about two types of data: scalars and arrays. Scalars are single pieces of information, while arrays are single variables containing many different values.
Alternatively, some things are better expressed as a set of one-to-one correspondences. A phone book, for example, is a set of correspondences between addresses and phone numbers. In Perl, structures like the phone book are represented as a hash. Some people call them associative arrays because they look a bit like arrays where each element is associated with another value. Most Perl programmers find that a bit too long-winded, and end up just calling them hashes.
Comparing a hash to a phone book is helpful, but there is a slight difference in that a phone book is normally ordered—the names are sorted alphabetically. In a hash the data is totally unsorted and has no intrinsic order. In fact, it’s more like directory enquiries than a phone book, in that you can easily find out what the number is if you have the name. Someone else keeps the order for you, and you needn’t ask what the first entry is.
Here’s where a diagram helps:
A scalar is one piece of data. It’s like a single block. An array or a list is like a tower of blocks; it’s kept in order, and it’s kept together as a single unit. A hash, on the other hand, is more like the illustration above. It contains several pairs of data. The pairs are in no particular order, no pair is “first” or “top,” and they’re all scattered around the hash.