in reply to for loop localisation bug?

Just to add my 2 cents - it's important not to confuse
for $n (1 .. 100)
with
for($n = 1; $n <= 100; ++$n)
as the former is an alias for foreach with the localization of the loop variable enabled (for the reasons that have been cited above), and the latter a straight loop counter similar in semantics as C's for() loop.

This reminds me of being bitten by the following several years ago:

do { ..... last if $some_condition; } while($some_other_condition);
A C programmer would think nothing of this loop. It's a straight do/while loop with a break (or its perl equivalent) statement, right?

Wrong. last/next doesn't work in this situation, because it isn't really a do/while loop, but rather a do BLOCK with a post condition (the while($some_other_condition) could just as well have been an unless() or if()).

Michael

Replies are listed 'Best First'.
Re: Re: for loop localisation bug?
by demerphq (Chancellor) on Dec 29, 2003 at 19:00 UTC

    and the latter a straight loop counter similar in semantics as C's for() loop.

    The latter is essentially syntactic sugar for a while loop. Consider:

    for (my $n=1;$n<=10;$n++) { ... } # essentially becomes { my $n=1; while ($n<=10) { ... } continue { $n++; } }

    Its my understanding that the continue part of while was specifically introduced to provide the c-style for loop behaviour.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi


Re: Re: for loop localisation bug?
by calin (Deacon) on Dec 29, 2003 at 19:29 UTC
    Your post gave me some ideas. How about emulating BrowserUk's foreach, for devil's sake, with something like:

    my $n; for (my @tmp = (LIST); @tmp ? ($n = shift @tmp) || 1 : 0;) {...} print "Last \$n is: $n\n";

    The tradeoff is that you're iterating over copies, and you won't get aliasing.