start page | rating of books | rating of authors | reviews | copyrights

Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 4.3 The while/until Statement Chapter 4
Control Structures
Next: 4.5 The for Statement
 

4.4 The do {} while/until Statement

The while/until statement you saw in the previous section tests its condition at the top of every loop, before the loop is entered. If the condition was already false to begin with, the loop won't be executed at all.

But sometimes you don't want to test the condition at the top of the loop. Instead, you want to test it at the bottom. To fill this need, Perl provides the do {} while statement, which is just like the regular while [ 3 ] statement except that it doesn't test the expression until after executing the loop once. For example:

[3] Well, this statement is not quite true; the loop control directives explained in Chapter 9, Miscellaneous Control Structures , don't work for the bottom-testing form.

do {     statement_1;     statement_2;     statement_3; } while (some_expression);

Perl executes the statements in the do block. When it reaches the end, it evaluates the expression for truth. If the expression is false, the loop is done. If it's true, then the whole block is executed one more time before the expression is once again checked.

As with a normal while loop, you can invert the sense of the test by changing do {} while to do {} until . The expression is still tested at the bottom, but its sense is reversed. For some cases, especially compound ones, this is the more natural way to write the test:

$stops = 0; do {     $stops++;     print "Next stop? ";     chomp($location = <STDIN>); } until $stops > 5 || $location eq 'home';


Previous: 4.3 The while/until Statement Learning Perl on Win32 Systems Next: 4.5 The for Statement
4.3 The while/until Statement Book Index 4.5 The for Statement