WE
regret
that
a
press
of
matter
prevents
our
noticing
####
Found for, 1 times.
Found such, 1 times.
Found up, 1 times.
Found at, 2 times.
Found had, 1 times.
Found was, 1 times.
Cumulative total of all words found: 50
####
#!/usr/bin/perl
use strict;
use warnings;
my %histogram = map { $_ => 0 } qw(
a am an and are as at be been but by can co de do due each
); # hash of the words to find so we can do an O(1) lookup for them
while ( <> ) {
chomp;
for ( split ) {
# split returns a list we can use directly
tr/A-Z/a-z/;
# lowercase all input
print "$_\n";
$histogram{ $_ }++ if exists $histogram{ $_ };
# only store counts for words that matter
}
}
my $count=0;
foreach my $word ( keys %histogram ) {
# keys() will list the keys, and we've already taken care
# of making sure we don't have extra words stored.
# Now there's no need to do two loops and check an array
# against a hash.
if ($histogram{$word} >0) {
print "Found $word, $histogram{$word} times.\n";
$count = $count + $histogram{$word};
}
}
print "Cumulative total of all words found: $count\n";