in reply to Re: Hash problem - Perl noob
in thread Hash problem - Perl noob

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

Replies are listed 'Best First'.
Re^3: Hash problem - Perl noob
by tinita (Parson) on Sep 16, 2006 at 09:07 UTC
    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% --
Re^3: Hash problem - Perl noob
by ptum (Priest) on Sep 15, 2006 at 17:25 UTC

    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. :)