-3

Write a perl program that reads in a text file containing one word per line. Create a hash containing the words read as keys and the number of times they have been read as the value. Print out each word and its frequency.

print $ARGV[0]."\n";

open (FILE,$ARGV[0]);
while ($line = <FILE>)
{
        chomp($line);
        if (exists($count{$line}))
        {
            $count{$line}++;
        }
        else
        {
            $count{$line} = 1;
        }
}

while ( ($word,$occurrences) = each(%count))
{
    print $word."  ".$occurrences."\n";

}
  1. Shouldn't it be open INFILE instead of FILE?

  2. $count{$line}: what is the role of $count in here? Can't you just write $line++?

  3. Can you please explain this sentence?

    while ( ($word,$occurrences) = each(%count))
    
1
  1. The name given to the filehandle doesn't have any special meaning. Except perhaps when using STDOUT, STDIN or STDERR as filehandle names. FILE works the same as INFILE, though some people may prefer INFILE for readability. See Mat's tip below for a valuable insight into the matter of filehandles.
  2. %count is the hash that will be used to store the number of occurrences for each word.
  3. Perldoc page for each here. Basically, this line iterates over the key-value pairs of the hash and assigns the key to the $word variable and the key's value in the hash to the $occurrences variable.
  • 1
    Extra tip: Do not use bareword filehandles – Mat May 23 '13 at 12:43
  • for number two, i was asking about $line, not %count – luc May 23 '13 at 14:03
  • Well $line++ by itself would do no good. It would actually produce a nonsensical value by "incrementing" the last character in the variable. Remember that $line actually contains the contents of the file's line not the line number. What is done here, is that the %count hash entry keyed by the contents of the $line variable is incremented (because the number of occurrences has increased by one) and created with a value of '1' if it didn't exist before. – Joseph R. May 23 '13 at 14:04
  • @JosephR. ONe more question. what would be the $word keyvariable in here and $occurences keyvalue refer to in this example? thank you again! – luc May 23 '13 at 14:37
  • $word would be a word read from the file (this example seems to assume an input file with one word per line) and $occurrences would contain the number of times this word has occurred in the file because it's incremented every time the $word is encountered. – Joseph R. May 23 '13 at 14:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.