Control Structures

The for loop

Example:

Print all numbers between 30 and 80.

#!/usr/bin/perl

my $i;
for ($i = 30; $i <= 80; $i += 1) {
   print "$i\n";
}

Explanation:

Inside the parentheses there are three expressions for the loop variable (here called $i):

  1. Initial state of the loop variable.
  2. A condition to check before each repetition of the loop.
  3. Modification of the loop variable after each repetition of the loop.

Note: a for loop can always be written also using the while construct. e.g. for this example:

#!/usr/bin/perl

$i = 30;          # set initial state of $i

while ($i <= 80) {   # condition to test $i
   print "$i\n";
   $i += 1;         # modify $i
}


Table of Contents.
Previous | Next.