in reply to Hash problem - Perl noob

First off you don't need to put parens around your variables. And what is going wrong is you're trying to look up values from @phrase, when you don't need to. Here is how I would write this, following your style:

use strict; use warnings; my @phrase = ( 'apple', 'apple', 'banana', 'banana', pear', 'pear', 'kiwi', 'kiwi' ); my %wordfreq; # Here $i contains the actual value from @phrase foreach my $i ( @phrase ) { $wordfreq{$i}++; print "$i appears ", $wordfreq{$i}, "\n"; }

Frank Wiles <frank@revsys.com>
www.revsys.com

Replies are listed 'Best First'.
Re^2: Hash problem - Perl noob
by johngg (Canon) on Sep 15, 2006 at 19:09 UTC
    Did you really mean to put your print statement in the foreach my $i ( @phrase ) { ... } loop? I think you are going to get eight lines of running total information like

    apple appears 1 apple appears 2 banana appears 1 banana appears 2 pear appears 1 pear appears 2 kiwi appears 1 kiwi appears 2

    rather than a summary of the word frequencies. To get a summary you could do something like

    print qq{$_ appears $wordfreq{$_} times\n} for sort keys %wordfreq;

    after the foreach loop.

    Cheers,

    JohnGG

      Good catch! Sorry, was hurrying to finish up that post before I had to run out the door.

      Frank Wiles <frank@revsys.com>
      www.revsys.com