Your match is finding portions of a word: $key =~ /$i/ will match when $key is "elephant" and $i is "a" because "elephant" contains an "a". To match on whole words only, use /b (word boundary - see perlre) before and after your search term:
my %histogram; my @wordstofind = qw( a am an and are as at be been but by can co de do due each ); while (<DATA>) { my @currentline = split; $histogram{$_}++ for @currentline; } foreach my $i (@wordstofind) { while ( my ($key, $value) = each (%histogram) ) { if ($key =~ /\b$i\b/) { print "Found $key, $value times\n"; } } } __DATA__ hello, I am an elephant. I have a long trunk.
Output:
Found a, 1 times Found am, 1 times Found an, 1 times
In reply to Re: 'Simple' comparing a hash with an array
by FunkyMonk
in thread 'Simple' comparing a hash with an array
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |