Chapter 5. Hashes

What Is a Hash?

A hash[43] is like the array that we discussed earlier, in that it is a collection of scalar data, with individual elements selected by some index value. Unlike a list array, the index values of a hash are not small nonnegative integers, but instead are arbitrary scalars. These scalars (called keys) are used later to retrieve the values from the array.

The elements of a hash have no particular order. Consider them instead like a deck of filing cards. The top half of each card is the key, and the bottom half is the value. Each time you put a value into the hash, a new card is created. Later when you want to modify the value, you give the key, and Perl finds the right card. So, really, the order of the cards is immaterial. In fact, Perl stores the cards (the key-value pairs) in a special internal order that makes finding a specific card easy, so Perl doesn’t have to look through all the pairs to find the right one. You cannot control this order, so don’t try.[44]

[43] In older documentation, hashes were called “associative arrays,” but the Perl hackers got tired of a seven-syllable word for such a common item, so we replaced it with a much nicer one-syllable word.

[44] Actually, modules like IxHash and DB file do provide some ordering, but at the cost of a performance penalty.

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.