I have just started learning Perl scripting language and have a question.
In Perl, what is t开发者_运维百科he logical reason for having continue
block work with while
and do while
loops, but not with for
loop?
From http://perldoc.perl.org/functions/continue.html
If there is a continue BLOCK attached to a BLOCK (typically in a while or foreach ), it is always executed just before the conditional is about to be evaluated again, just like the third part of a for loop in C.
Meaning that in the for
loop, the third argument IS the continue expression, e.g. for (initialization; condition; continue)
, so therefore it is not needed. On the other hand, if you use for
in the foreach
style, such as:
for (0 .. 10) {
print "$i\n";
} continue { $i++ }
It will be acceptable.
I suspect that the continue
block isn't used in for
loops since it is exactly equivalent to the for
loop's 3rd expression (increment/decrement, etc.)
eg. the following blocks of code are mostly equivalent:
for ($i = 0; $i < 10; $i++)
{
}
$i = 0;
while ($i < 10)
{
}
continue
{
$i++;
}
You can use a continue
block everywhere it makes sense: with while
, until
and foreach
loops, as well as 'basic' blocks -- blocks that aren't part of another statement. Note that you can use the keyword for
instead of foreach
for the list iteration construct, and of course you can have a continue
block in that case.
As everybody else said, for (;;)
loops already have a continue
part -- which one would you want to execute first?
continue
blocks also don't work with do { ... } while ...
because syntactically that's a very different thing (do
is a builtin function taking a BLOCK as its argument, and the while
part is a statement modifier). I suppose you could use the double curly construct with them (basic block inside argument block), if you really had to:
do {
{
...;
continue if $bad;
...;
}
continue {
...; # clean up
}
} while $more;
精彩评论