| | |||||||
| |||||||
| |||||||
|
|
|
|
|
|
|
Control Flow Constructs: the For and Foreach Loops - The foreach Loop(Page 2 of 2 ) Perl has another loop called the foreachloop. It is used to loop through lists and arrays. We will talk about arrays in the next chapter, but since we have seen examples of a list, we can look at theforeachloop processing a list of numbers: #!/usr/bin/perl -w use strict; my $number; foreach $number (1 .. 10) { Theforeachloop executes the body of the loop (theprint()function in this example) for each number in the list.$numberis called the loop control variable, and it takes on the values in the list, one at a time. Recall that(1 .. 10)is shorthand for(1, 2, 3, 4, 5, 6, 7, 8, 9, 10). This code produces this result: $ perl foreach.pl A note about the keywordsforandforeach: they are synonyms for each other. In other words, we can say foreach ($i = 1; $i <= 10; $i++)_ { .. } and for $number (1..10) { .. } foreach is rarely used in place offor, butforis often used instead offoreach. In the spirit of minimal confusion, we will spell outforeachwhen we have aforeachloop. We will talk more aboutforeachin the next chapter when we discuss the array data type. do .. while and do .. until When we were categorizing our lists, we divided indefinite loops into those that execute at least once and those that may execute zero times. The whileloop we’ve seen so far tests the condition first, and so if the condition isn’t true the first time around, the “body” of the loop never gets executed. There’s two other ways to write our loop to ensure that the body is always executed at least once: do { action } while ( condition ); Now we do the test after the block. This is equivalent to moving the diamond in our flow chart from the top to the bottom. Here is an example: #!/usr/bin/perl -w use strict; my $i = 1; print "starting do...while:\n"; $i = 1; print "starting do...until\n"; Executing this program produces the following: $ perl dowhiledountil.pl The importance of thedo..whileanddo..untilloop is that the body of the loop is always executed at least once. Please check back next week for the continuation of this article.
|
| |
| |