Hashes Versus Arrays and Lists

You learned yesterday that a list is a collection of scalars, and that an array is an ordered list, indexed by element. A hash is also a way of expressing a collection of data, but the way the data is stored is different.

A hash is an unordered collection of pairs of scalars, often called keys and values (See Figure 5.1). You access an element (a value) in a hash by referring to it by its key. Neither the keys or the values are in any kind of order; you cannot refer to the first or last element in a hash, nor can you numerically iterate over the elements in that hash, like you can an array (although you can get a list of the hash's keys, of its values, or of both in pairs, and access all a hash's elements that way). Hashes are more useful than arrays in many ways, most typically because it's easier to keep track of elements in named slots (keys in hashes) rather than by numbers (indexes in arrays).

Figure 5.1. Hashes.


Note

Hashes are sometimes called associative arrays, which is actually a better description of what they do (the keys are associated with their values). In fact, associative arrays are the original name for hashes, but today's Perl programmers prefer to call them by the much shorter and less awkward name hash.


As with arrays, hashes have their own variables with their own symbol at the beginning. Hash variables start with a percent (%), and follow all the same rules as array variables do. As with all variables, the hash variable %x is a different thing than the array variable @x or the scalar variable $x.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset