Loop Control
We mentioned that you can put a LABEL on a
loop to give it a name. The loop’s LABEL
identifies the loop for the loop-control operators next, last, and redo. The LABEL
names the loop as a whole, not just the top of the loop. Hence, a
loop-control operator referring to the loop doesn’t actually “go to”
the loop label itself. As far as the computer is concerned, the
label could just as easily have been placed at the end of the loop.
But people like things labelled at the top, for some reason.
Loops are typically named for the item the loop is processing
on each iteration. This interacts nicely with the loop-control
operators, which are designed to read like English when used with an
appropriate label and a statement modifier. The archetypal loop
works on lines, so the archetypal loop label is LINE:, and the archetypal loop-control
operator is something like this:
next LINE if /^#/; # discard comments
The syntax for the loop-control operators is:
last LABEL next LABEL redo LABEL
The LABEL is optional; if omitted,
the operator refers to the innermost enclosing loop. But if you want
to jump past more than one level, you must use a
LABEL to name the loop you want to
affect. That LABEL does not have to be in
your lexical scope, though it probably ought to be. But, in fact,
the LABEL can be anywhere in your dynamic
scope. If this forces you to jump out of an eval or subroutine, Perl issues a warning
(upon request).
Just as you may have as many return operators in a function as you ...
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