next up previous contents
Next: Hashes and Lists Up: Hashes Previous: Hashes   Contents

What is a hash?

A hash, variously known as an associative array or a dictionary, is very similar to the arrays discussed in Chapter 4. The principal difference is that, while arrays are indexed by consecutive integers, hashes can be indexed by any scalar value. The value used to index a hash is known as a key. Most often strings are used as keys in hashes. This makes it very easy to store information about things in a hash, since we usually identify different things by a string (like a name), rather than one of a set of consecutive integers.

In perl, hashes are represented by variables whose names begin with a percent sign (%). Just as with arrays, however, the percent sign is only used when you're refering to the entire hash. To access a element of a hash (which must be a scalar), begin the name with a dollar sign ($) just as with an array, but, instead of using square brackets to enclose the index, use curly braces ({ and }) to enclose the index. Perl treats barewords inside these curly braces a little differently than the way described in Section 3.1; barewords are treated as character strings even if there is a function with the same name. This rule applies only to strings without blanks or other special characters; if a key contains such characters it must be enclosed in quotes, with the usual rules for quoted strings (Section 3.1) in effect. Of course, you can always enclose string values for keys in quotes, and many perl programmers do just that.

If you refer to a scalar element of a hash, perl will create the hash if it doesn't already exist. If you want to explicitly create an empty hash, use an empty set of parentheses(()).


next up previous contents
Next: Hashes and Lists Up: Hashes Previous: Hashes   Contents
Phil Spector 2002-10-18