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


In reply to Re: 'Simple' comparing a hash with an array by TGI
in thread 'Simple' comparing a hash with an array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.