while loops evaluate a logical expression and execute a
statement block repeatedly as long as the logical expression
evaluates to true
. The expression is evaluated first
at the beginning of the of the loop, and again after each execution
of the statement block.
Copy the text below and run it as a Perl script.
# the following 'while' loop works just like a 'for' loop; # $i is a control variable and is initialized as 0; # the expression after the reserved word 'while' is # tested before the first iteration, and the following # code block is executed if it evaluates to 'true'; # at the end of the following statement block the expression # is re-evaluated and the block is executed again if the # condition is still 'true' $i = 0; while ($i <= 100) # loop control condition { print "iteration $i\n"; $i = $i + 1; }
The behavior of all loops, including for
and foreach
, can be manipulated by the following
reserved words: next and last.
next skips all subsequent statements in the
statement block and re-evaluates the loop condition. If this
condition still evaluates to true
, the next iteration
will start.
last will terminate a loop; the program will
resume execution after the statement block in which
last
occurs.
$i = 0; while ($i++ <= 100) # loop control condition { next if ($i % 5 != 0); # The modulus operator '%' divides # the integer to the left by the # integer on the right and returns # the remainder. # If the number is not divisible by 5 # (the remainder is not 0), the loop # will immediately move on to the next # iteration without executing any # statements that follow it print "iteration $i\n"; last if ($i == 90); # the 'last' keyword ends the loop # even if the initial condition is # still true }
The following example does essentially the same as the preceding one, but the next
and last
statements have been built into an if/elsif/else
construct.
$i = 0; while ($i++ <= 100) { if ($i == 90) { print "\'last\' called at $i\n"; last; } elsif ($i % 5 == 0) { print "iteration $i\n"; } else { next; } }