Useful Things to Do with a Hash

Hashes are often used in Perl for more reasons than to store records by keys for later retrieval. The advantages to using a hash are fast individual access to keys and the fact that all keys in a hash are unique. These properties lend themselves to some useful data manipulations. Not surprisingly, because arrays and hashes are so similar, many of the interesting things you can do with hashes are array manipulations.

Determining Frequency Distributions

In Hour 6, “Pattern Matching,” you learned how to take a line of text and split it into words. Examine the following snippet of code:

while ( <> ) {
   while ( /(\w[\w-]*)/g  ) {   # Iterate over words, setting $1 to each.
         $Words{$1}++;
   }
}

The first line reads the standard ...

Get SAMS Teach Yourself Perl in 24 Hours THIRD EDITION now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.