Iterating through a list is more efficient than looping over an index variable. This is because all the index keeping is done internally, where as the index variable solution has to do a lot of external operations (see. more CPU time).

Also you can't accidentally offset the index within the iterative code e.g

for(my $i = 0; $i < @ARGVl $i++) { if($ARGV[$i] =~ /meets some condition/) { # ack! the index has been offset $i += 2; } }
Compared to
for my $i (0 .. $#ARGV) { if($ARGV[$i] =~ /meets some condition/) { # doesn't matter as $i will be set again in the next iteration $i += 2; } }
This works both ways however as you may want to intentionally affect the offset, but you're possibly better off using a while loop in the first place.

Here's a quick benchmark for those in need of speed

use Benchmark qw(cmpthese); my @list = 1..10000; my $r; cmpthese(-10, { cstyle => sub { for(my $i = 0; $i < @list; $i++) { $r = $list[$i]; } }, perlstyle => sub { for my $i (@list) { $r = $i; } } }); __output__ Benchmark: running cstyle, perlstyle, each for at least 10 CPU seconds +... cstyle: 15 wallclock secs (10.57 usr + 0.05 sys = 10.62 CPU) @ 36 +.06/s (n=383) perlstyle: 15 wallclock secs (10.10 usr + 0.03 sys = 10.13 CPU) @ 86 +.77/s (n=879) Rate cstyle perlstyle cstyle 36.1/s -- -58% perlstyle 86.8/s 141% --

HTH

_________
broquaint

update: added benchmark because it's just so darned easy


In reply to Re: for ( ; ; ) vs for ( .. ) by broquaint
in thread for ( ; ; ) vs for ( .. ) by Popcorn Dave

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.