1. Technology

For Loop - Beginning Perl Tutorial, Control Structures

Examples of Perl's For Loop


As we've discussed, Perl's for loop, or for statement, is used to loop through a designated block of code until a specific condition is met. Let's look at an example of Perl's for loop in action and break down exactly how it works, step by step.
 for ($count = 10; $count >= 1; $count--) {
 	print "$count ";
 print "Blastoff.\n"; 
Running this simple Perl script produces the following output:
 10 9 8 7 6 5 4 3 2 1 Blastoff. 
The controlling part of the for loop is broken down into three parts inside the parenthesis. First we set the initial expression, in this case setting $count to a value of 10.
 $count = 10; 
Next is the test expression - this expression is evaluated true or false on each repetition of the for loop. If the test evaluates to true the code is executed. If the test expression evaluates false the block of code is not executed and the program continues past the for loop. The test is to see if $count is greater than or equal to 1.
 $count >= 1; 
Finally at the end of each repetition of the for loop, the initial expression is reset in some way. In this example, $count is decremented (reduced) by one each time.
  1. $count is set to a value of 10.
  2. Is $count greater than or equal to 1? If so, continue, otherwise exit the for loop.
  3. Execute the code block inside the for loop.
  4. Reduce the value of $count by 1.
  5. Return to step 2.
The end result is that $count starts at 10 and comes down by 1 every time the loop is executed. When we print the value of $count, we can see that the loop is executed all the way up to $count having a value of 1, at which point the loop stops and the word 'Blastoff' is printed.
  1. A for loop is a Perl control structure.
  2. It is used to step through a block of code a specific number of times.
Previous: How to use a for loop in Perl
  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. For Loop - Beginning Perl Tutorial, Control Structures

©2014 About.com. All rights reserved.