home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


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 the same as that after 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, more commonly you create and access the hash 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 notation 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.