Control Structures

The for loop

Example:

Print all multiples of 10 between 30 and 80.

#!/usr/local/bin/perl
use strict 'vars';
use warnings;

my $i;
for ($i = 30; $i <= 80; $i += 10) {
   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 thewhile construct. e.g. for this example:

#!/usr/local/bin/perl
use strict 'vars';
use warnings;

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

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


Table of Contents.
Next.