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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.