Perl Programming Page 5 - Perl 101 (Part 3) - Looping The Loop |
Both "while" and "until" are typically used when you don't know for certainhow many times the program should loop - in the examples above, forexample, the program continues to loop until the user enters the rightanswer. But Perl also comes with a mechanism for executing a set ofstatements a specific number of times - and it's called the "for" loop: Doesn't make any sense? Well, the "counter" here refers to a scalarvariable that is initialized to a specific numeric value [usually 0 or 1];this counter is used to keep track of the number of times the loop has beenexecuted. Each time the loop is executed, the "condition" is tested for validity. Ifit's found to be valid, the loop continues to execute and the value of thecounter is updated appropriately; if not, the loop is terminated and thestatements following it are executed. Take a look at this simple example of how the "for" loop can be used: Here's what the output looks like: How does this work? We've begun by initializing the variable $a to 5. Eachtime the loop is executed, it checks whether or not $a is less than 12; ifit is, a line of output is printed and the value of $a is increased by 1 -that's where the $a++ comes in. Once the value of $a reaches 12, the loopis terminated and the line following it is executed. And, for something slightly more complex, take a look at our re-write ofthe factorial calculator above:
This article copyright Melonfire 2000. All rights reserved.
blog comments powered by Disqus |