while and until Statements
The while statement
repeatedly executes the block as long as
EXPR is true. If the word while is replaced by the word until, the sense of the test is reversed;
that is, it executes the block only as long as
EXPR remains false. The conditional is
still tested before the first iteration, though.
The while or until statement can have an optional extra
block: continue. This block is
executed every time the block is continued, either by falling off
the end of the first block or by an explicit next (a loop-control operator that goes to
the next iteration). The continue
block is not heavily used in practice, but it’s in here so we can
define the three-part loop rigorously in the next section.
Unlike the foreach loop
we’ll see in a moment, a while
loop has no official “loop variable”.[75] You may, however, declare variables explicitly. A
variable declared in the test condition of a while or until statement is visible only in the
block or blocks governed by that test. It is not part of the
surrounding scope. For example:
while (my $line = <STDIN>) {
$line = lc $line;
}
continue {
print $line; # still visible
}
# $line now out of scope hereHere, the scope of $line
extends from its declaration in the control expression throughout
the rest of the loop construct, including the continue block, but not beyond. If you
want the scope to extend further, declare the variable before the
loop.
[75] A consequence of this is that a while never implicitly localizes any variables in ...
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