"Perl for Perl Newbies" - Part 1The For Loop

6. The For Loop

The for loop enables us to iterate over a sequence of numbers and repeat the same set of operations for each number.

For example, the following program prints all the numbers from 1 to 100:

for $i (1..100)
{
    print $i, "\n";
}

Some explanations about the syntax:

  1. $i is the iteration variable. It receives the value 1, then the value 2, then 3 and so forth until it is equal to 100, afterwards the loop terminates.
  2. The curly brackets ({ ... }) encapsulate the loop block. The loop block is executed once for each value $i accepts. Within that block, called the loop body, you can use $i and you'll get its current value.

We can nest loops, so for example the following program prints the multiplication board:

for $y (1 .. 10)
{
    for $x (1 .. 10)
    {
        $product = $y*$x;
        # Add as much whitespace as needed so the number will occupy
        # exactly 4 characters.
        for $whitespace (1 .. (4-length($product)))
        {
            print " ";
        }
        print $product;
    }
    # Move to the next line
    print "\n";
}

You may have noticed the program's comments. In perl comments start with the sharp sign (#) and extend to the end of the line. Writing the multiplication boards with the labels that indicate which numbers are being multiplied is left as an exercise to the reader.


Written by Shlomi Fish