In this one, we declared all of the variables at the top. People who
come to Perl from a background in languages like Pascal (where
variables are always declared "at the top") may find that
way more familiar than declaring variables as they are needed. Of
course, we're declaring these because we're pretending
that use strict may be in effect; by default, Perl
won't require such declarations.
Now, the first foreach loop goes through all of the words. That loop
contains the most important statement of the entire program, the
statement that says to add one to $count{$word},
and put the result back into $count{$word}.
Although you could write it either the short way (with the
+= operator) or the long way, the short way is
just a little bit more efficient, since Perl has to look up
$word in the hash just once.[384]
For each word in the first foreach loop, we add
one to $count{$word}. So, if the first word is
fred, we add one to
$count{"fred"}. Of course, since this is the first
time we've seen $count{"fred"}, it's
undef. But since we're treating it as a
number (with the numeric += operator, or with
+, if you wrote it the long way), Perl converts
undef to 0 for us,
automatically. The total is 1, which is then
stored back into $count{"fred"}.
The next time through that foreach loop,
let's say the word is barney. So, we add one
to $count{"barney"}, bumping it up from
undef to 1, as well.
Now let's say the next word is fred again.
When we add one to $count{"fred"}, which is
already 1, we get 2. This goes
back into $count{"fred"}, meaning that we've
now seen fred twice.
When we finish the first foreach loop, then,
we've counted how many times each word has appeared. The hash
has a key for each (unique) word from the input, and the
corresponding value is the number of times that word appeared.
So now, the second foreach loop goes through the
keys of the hash, which are the unique words from the input. In this
loop, we'll see each different word once.
For each one, it says something like "fred was seen 3
times."
If you want the extra credit on this problem, you could put
sort before keys to print out
the keys in order. If there will be more than a dozen items in an
output list, it's generally a good idea for them to be sorted,
so that a human being who is trying to debug the program will fairly
quickly be able to find the item he or she wants.