in reply to Hash problem - Perl noob

Hi, when using for $i (@phrase), the variable $i becomes an alias for all the elements in the list @phrase. In the first run it contains "apple", then "apple" , then "banana" , etc.. If you have this construct, you don't need the additional counter $j. A bit shorter would be:
for my $elem (@phrase) { $wordfreq{$elem}++; }
# or even shorter, but perhaps a bit unreadable: $wordfreq{$_} for (@phrase);
Update: Thanks to chargrill for pointing out my typo, indeed it should be:
$wordfreq{$_}++ for (@phrase);
When printing out the results you might want to print out the name of what you found, for example:
foreach my $key (sort keys %wordfreq) { print "$key: $wordfreq{$key}\n"; }
Hope this was the answer you were looking for. Cheers Roland

Replies are listed 'Best First'.
Re^2: Hash problem - Perl noob
by chargrill (Parson) on Sep 15, 2006 at 18:01 UTC
    # or even shorter, but perhaps a bit unreadable: $wordfreq{$_} for (@phrase);

    I think perhaps you meant:

    $wordfreq{$_}++ for (@phrase);

    Since, after all, it's supposed to count the frequency of each word :)



    --chargrill
    s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)