Previous | Table of Contents | Next |
LoopingAs you read in the Introduction, sometimes just making decisions and running code conditionally are not enough. Often you need to run pieces of code over and over again. The exercise presented in Listing 3.1 wasn't much fun because you could take only one guess (well, that and because it's a pointless game). If you want to be able to take multiple guesses, you need to be able to repeat sections of code conditionally, and that's what looping is all about. Looping with whileThe simplest kind of loop is a while loop. A while loop repeats a block of code as long as an expression is true. The syntax for a while loop looks like this: while (expression) block When Perl encounters the while statement, it evaluates the expression. If the expression is true, the block of code is run. Then, when the end of the block is reached, the expression is re-evaluated. If it's still true, the block is repeated, as in the following snippet: Listing 3.2. Sample while Loop1: $counter=0; 2: while ($counter < 10 ) { 3: print "Still counting...$counter\n"; 4: $counter++; 5: }
Looping with forThe for statement is the most complicated and versatile of Perl's looping constructs. The syntax looks like this: for ( initialization; test; increment ) block The three sections of the for statement—initialization, test, and increment—are separated by semicolons. When Perl encounters a for loop, the following sequence takes place:
The following is an example of a for loop: for( $a=0; $a<10; $a=$a+2 ) { print "a is now $a\n"; } In this snippet, $a is set to 0, and the test $a<10 is performed and found to be true. The body of the loop prints a message. The increment is then run—$a=$a+2—which increases the value of $a by 2. The test is performed again, and the loop repeats. This particular loop repeats until the value of $a is 10, when the test will be false and the program will continue running after the for loop. You don't have to use the increment in the for statement for counting; it simply iterates until the test is false. In fact, you should be aware that each of the three parts of the for statement is optional, although the two semicolons are required. The following for statement is missing some pieces but is still perfectly valid: $i=10; # initialization for( ; $i>-1; ) { print "$i.."; $i--; # actually, a decrement. } print "Blast off!\n"; Omitting the test portion means that you have to have some other way to exit the loop, or it will loop forever. |
Previous | Table of Contents | Next |