Useful Hash Examples

If you have not seen hashes before, you might be amazed at the places where they can be used. The following examples show some application areas where this data type is useful. Notice in these examples that the hashes are built dynamically in response to the requirements of the program. This is different from the %groups hash above, where that hash was initialized before accepting user input.

Counting Words in a File

This example demonstrates how to use a hash to count the frequency of words in a file. The strategy is to read lines from a file and split each line into its words. Then each word can be used as an index into a hash where the associated value can be the count for each word. Here is the code. See the folder Freq.


% type freq.pl
#
#       freq.pl
#
while(<STDIN>)
{       @words = split;
        foreach $word (@words)
        {
             $words{$word}++;
        }
}
foreach $word (sort(keys(%words)))
{
        print "$word occurred $words{$word}
";
}
%

The important piece of code above is

$words{$word}++;

which is of course a shortcut for

$words{$word} = $words{$word} + 1

and which simply adds 1 to the count for the word indexed by $word.

Finding Unique Words

In the next example, we wish to record the unique words in a document. We do this by examining each word found in the input to determine whether it has been seen already. If it has not been seen, we simply add it to the hash and associate some value with it, a 1 in this case. The next time this word is encountered, it will already have been marked as seen. In the end, we just print out the keys. See the folder Uniq.


% type uniq.pl
#
#       uniq.pl
#
while(<STDIN>)
{
   @words = split;
   foreach $word (@words)
   {
          $seen{$word} = 1 if (!exists($seen{$word}));
   }
}
print join("
", sort(keys(%seen)));
%

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.174.55