If I structure a solution as a c, java, or BASIC programmer might:
my %word_list = ( bat=> 0, cat=> 0, eat=> 0, fat=> 0 ); my @words = qw( bat bat dat fat eat eat eat fat ); my $word; foreach $word (@words){ if(exists $word_list{$word}){ $word_list{$word}= $word_list{$word} + 1; } else{ $word_list{$word} = 1; } } foreach $word (sort keys %word_list) { print "$word: $word_list{$word}\n"; }
If I want a perlish solution I would write:
%word_list = ( bat=> 0, cat=> 0, eat=> 0, fat=> 0 ); my @words = qw( bat bat dat fat eat eat eat fat ); my $word; foreach $word (@words){ $word_list{$word}++; } foreach $word (sort keys %word_list) { print "$word: $word_list{$word}\n"; }
If don't need a the original word_list for displaying words that were not matched (word count is 0) but want only the counts of the words that occur in @words then an empty %word_list.
my %word_List = ( );
Using a hash and increment to count things is a fundamental technique to master early in your perl walk.

RBL


In reply to Re: hard referencing in hashes?!? by LEFant
in thread hard referencing in hashes?!? by imlou

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.