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
|