Perl tips: Understanding flow control
Last, next, redo
The example in Listing A demonstrates the behavior of these three
statements.
Listing A will output:
in block - iteration 1
in block - iteration 2
past redo
in block - iteration 3
past redo
In the first iteration, $redo is set to 1, and the redo takes effect, so the output is in block - iteration 1. In the second iteration, $redo becomes 2, so the redo is not executed and the output is in block - iteration 2 and past redo. Since $next is set to 1, the next statement is executed, but the rest of the block is not executed. In the third iteration, $next becomes 2, and the next statement is not executed, allowing the last statement to execute. Again, the output is in block - iteration 3 and past redo.
When is the continue block executed?
We've discussed the use of the last, next, and redo
statements to control the flow of execution within a block. But a less
well-known aspect is that execution blocks have an optional
continue block attached to them. The continue block is typically
used in a while or for each, but it can be used in a plain block
as well. The continue block is executed right before the conditional is
reevaluated. Similar to the third part of a for loop in C, it can be used
to increment a loop variable even when the loop execution has been interrupted
with the next statement.
In Listing B, we build on the example in Listing A to show when the continue block gets executed.
This block outputs:
in block - iteration 1
in block - iteration 2
past redo
continue
in block - iteration 3
past redo
The output shows that the continue block is not executed when the redo statement is used in the first iteration. In the second iteration, the continue block is executed after the next statement is executed. It is not executed after a last statement.