in reply to Hash problem - Perl noob

You seem to be stepping through the contents of @phrase with an i-based for loop, yet you're referring to the jth element in @phrase. You need to make up your mind ... are you iterating through @phrase with i or with j?

I think either of these (untested) would do what you want:

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

or this:

for (my $i=0;$i<=$#phrase;$i++) { $wordfreq{$phrase[$i]}++; }

No good deed goes unpunished. -- (attributed to) Oscar Wilde

Replies are listed 'Best First'.
Re^2: Hash problem - Perl noob
by ikegami (Patriarch) on Sep 15, 2006 at 16:58 UTC

    Why
    for (my $i=0;$i<=$#phrase;$i++)
    over the equally efficient yet much more readable
    for my $i (0 .. $#phrase)

      over the equally efficient ...
      i think a "foreach loop" is more efficient, but maybe i'm making a mistake in my benchmark?
      perl -wle' use Benchmark; my $max = $ARGV[0]; timethese($ARGV[1]||-1, { for => sub { for (my $i=0;$i<$max;$i++) { 1 } }, foreach => sub { for my $i (0..$max-1) { 1 } }, } )' 10000 2000 Benchmark: timing 2000 iterations of for, foreach ... for: 8 wallclock secs ( 7.63 usr + 0.00 sys = 7.63 CPU) @ 26 +2.12/s (n=2000) foreach: 5 wallclock secs ( 5.38 usr + 0.00 sys = 5.38 CPU) @ 37 +1.75/s (n=2000)
        I thought it might be. You test looks fine, and I'm getting similar results.
        Rate for foreach for 531/s -- -38% foreach 854/s 61% --

      No good reason ... personal style (or lack thereof), "that's the way I originally learned it", etc. Thanks for reminding me (and the OP) of a better alternative. :)