Learning Perl

Learning PerlSearch this book
Previous: 5.1 What Is a Hash?Chapter 5
Hashes
Next: 5.3 Literal Representation of a Hash
 

5.2 Hash Variables

A hash variable name is a percent sign (%) followed by a letter, followed by zero or more letters, digits, and underscores. In other words, the part after the percent is just like what we've had for scalar and array variable names. And, just as there is no relationship between $fred and @fred, the %fred hash variable is also unrelated to the other two.

Rather than referencing the entire hash, the hash more commonly is created and accessed by referring to its elements. Each element of the hash is a separate scalar variable, accessed by a string index, called the key. Elements of the hash %fred are thus referenced with $fred{$key} where $key is any scalar expression. Notice once again that accessing an element of a hash requires different punctuation than when you access the entire hash.

As with arrays, you create new elements merely by assigning to a hash element:

$fred{"aaa"} = "bbb"; # creates key "aaa", value "bbb"
$fred{234.5} = 456.7; # creates key "234.5", value 456.7

These two statements create two elements in the hash. Subsequent accesses to the same element (using the same key) return the previously stored value:

print $fred{"aaa"}; # prints "bbb"
$fred{234.5} += 3;  # makes it 459.7

Referencing an element that does not exist returns the undef value, just as with a missing array element or an undefined scalar variable.


Previous: 5.1 What Is a Hash?Learning PerlNext: 5.3 Literal Representation of a Hash
5.1 What Is a Hash?Book Index5.3 Literal Representation of a Hash