Naturally there's always more than one way to do it.

Your way (for loop):

for ( # Lexical scope my($idx,$x,$y)=(0,0,0); # Initializer $idx<10; # Condition ++$idx, $x+=2, $y+=3 # Prep for next iteration. ) { print "$idx, $x, $y\n"; }

...which is exactly the same as (while loop):

{ # Lexical scope my( $idx, $x, $y ) = ( 0, 0, 0 ); # Initializer while( $idx < 10 ) { # Condition print "$idx, $x, $y\n"; } continue { # Prep for next iteration. ++$idx; $x += 2; $y += 3; } }

It's up to you to decide which is more legible and maintainable. I think probably the while loop. Both loops are explicit in what they do, but the while loop, with its "continue" block is visually striking so that the fact that several variables are being incremented is not so easy to miss.

Both are probably proof that it's possible to write C in Perl. ;) But I can't think of a more elegant approach at the moment. I guess that must say something about where I've been spending too much time.

Update: By the way, if you pass the above code samples through B::Deparse, you'll find that they decompose almost identically:

$ perl -MO=Deparse,-x9 ./mytest.pl # Decomposition of the "for" loop: while ($idx < 10) { print "$idx, $x, $y\n"; } continue { ++$idx, $x += 2, $y += 3 } # Decomposition of the "while" loop (essentially it's unchanged): { my($idx, $x, $y) = (0, 0, 0); while ($idx < 10) { print "$idx, $x, $y\n"; } continue { ++$idx; $x += 2; $y += 3; } } ./mytest.pl syntax OK

Dave


In reply to Re: Increment by 2 and by 1 in same loop. by davido
in thread Increment by 2 and by 1 in same loop. by freekngeek

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.