in reply to 'Simple' comparing a hash with an array

One problem leaps out at me immediately, you aren't chomping your input lines. Sometimes you'll end up with words like "at\n" in your histogram.

while (defined (my $line = <STDIN> )) { chomp $line; my @currentline = split /\s+/, $line; $histogram{$_}++ for @currentline; }

Another basic issue, why do you iterate over your histogram hash? This sort of thing is exactly what hashes are designed to allow you to avoid. Just test for existence, and retrieve the value as needed. I

if( exists $histogram{$word} ) { print "Found $word, $histogram{$word} times\n"; }

Update: ysth is right. The chomp is not needed. split seems to be especially hungry. I was expecting it to match like the code below.

use Data::Dumper; __END__ #Result: while ( <STDIN> ) { my @foo = /(\s+)/; print Dumper \@foo; } C:\> test.pl cat food $VAR1 = [ ' ' ];


TGI says moo

Replies are listed 'Best First'.
Re^2: 'Simple' comparing a hash with an array
by ysth (Canon) on Apr 17, 2008 at 00:27 UTC
    One problem leaps out at me immediately, you aren't chomping your input lines. Sometimes you'll end up with words like "at\n" in your histogram.
    Nope. Try it. \n is whitespace, which is consumed by the split.