Three-Part Loops
The three-part loop[76] has three semicolon-separated expressions within its parentheses. These three expressions are interpreted respectively as the initialization, the condition, and the reinitialization of the loop. The parentheses around them and the two semicolons between them are required, but the expressions themselves are optional. The initializer and reinitializer do nothing if omitted. The condition, if omitted, is considered to have a true value. (The values of the initializer and reinitializer don’t matter since they are evaluated only for their side effects.)
The three-part loop can be defined in terms of the
corresponding while loop,
relocating its three expressions. When you say this:
LABEL:
for (my $i = 1; $i <= 10; $i++) {
...
}it gets rearranged internally to work like this:
{
my $i = 1;
LABEL:
while ($i <= 10) {
...
}
continue {
$i++;
}
}(except that there’s not really an outer block; we just put
one there to show how the scope of the my is limited).
If you want to iterate through two variables simultaneously, just separate the parallel expressions with commas:
my $i;
my $bit;
for ($i = 0, $bit = 0; $i < 32; $i++, $bit <<= 1) {
say "Bit $i is set" if $mask & $bit;
}
# the values in $i and $bit persist past the loopOr to declare those variables to be visible only inside the loop:
for (my ($i, $bit) = (0, 1); $i < 32; $i++, $bit <<= 1) {
say "Bit $i is set" if $mask & $bit;
}
# loop's versions of $i and $bit now out of scopeBesides the normal looping ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access