next up previous contents
Next: Hashes Up: Control Structures Previous: The for statement   Contents


Control within Loops

When writing a loop, there are often times when you need to take action immediately inside the loop, without allowing the rest of the statements in the loop's body to execute, or without waiting for the termination condition to be checked. The two basic operations that you'll want to do in a situation like that are to either exit the loop entirely (perl's last statement), or to simply skip the remainder of the current interation of the loop, and go on to the next (perl's next statement). C programmers will immediately recognize the parallel between the next statement and C's continue statement, and between the last statement and C's break statement. These statements can be used in any of the loops described in the previous sections. For each of the loops, the last statement immediately transfers control to the statement immediately following the loop. For the while loop, the next statement skips over the remaining statements of the loop, tests the while loop's expression, and continues in the usual way. The behavior of the next statement in a foreach loop is similar; the remaining statements are skipped,var is advanced to its next value, and execution resumes at the top of the loop. When a next statement occurs inside a for loop, the remaining statements are skipped, the updating statements in expression-3 of the loop are performed, and the termination condition expression-3 is tested to see if execution should continue.

When there is a condition that can be easily tested to determine when a loop ends, placing a test for that condition on the while statement is usually the most intuitive way to implement the loop. But as the criteria for terminating the loop become more complex, it's sometimes inconvenient to try to write the loop that way. In situations like this, many perl programmers write an infinite loop, and control termination with next or last statements inside the loop. When you write a loop like this, it's very important to make sure that there is a last statement inside the loop somewhere, to make sure the loop eventually terminates. Suppose we wish to print names from a list until either we encounter the name ``END'' or we process 10 names. We could write an infinite loop to handle it like this:

     $count = 0;
     while(1){
        last if $count > 10;
        last if $name[$count] eq 'END';
        print "$name[$count]\n";
        $count++;
     }
The value 1 is guaranteed to be true, so the only way the loop can terminate is through the last statements.
next up previous contents
Next: Hashes Up: Control Structures Previous: The for statement   Contents
Phil Spector 2002-10-18