Note

foreach is frequently abbreviated as for.

while while performs a block of statements as long as a particular condition is true:

Remember that the condition can be anything that returns a true or false value. For example, it could be a function call:

while ( InvalidPassword($user, $password) ) {

print "You've entered an invalid password. Please try again.\n"; $password = GetPassword;

until until is the exact opposite of the while statement. It performs a block of statements as long as a particular condition is falseor, rather, until it becomes true:

until (ValidPassword($user, $password)) {

print "You've entered an invalid password. Please try again.\n"; $password = GetPassword;

last and next

You can force Perl to end a loop early by using a last statement. last is similar to the C break commandthe loop is exited. If you decide you need to skip the remaining contents of a loop without ending the loop itself, you can use next, which is similar to the C continue command. Unfortunately, these statements don't work with do ... while.

On the other hand, you can use redo to jump to a loop (marked by a label) or inside the loop where called:

if (($a = $a / 2) > 2) { print "$a\n"; if (—$a < 2) {

exit;

redo TEST;

In this simple example, the variable $a is repeatedly manipulated and tested in an endless loop. The word start will only be printed once.

The while and until loops evaluate the conditional first. The behavior is changed by applying a do block before the conditional. With the do block, the condition is evaluated last, which results in the contents of the block always executing at least once (even if the condition is false). This is similar to the C language do ... while (conditional) statement.

4 PREV

NEXT

Was this article helpful?

0 0

Post a comment