Loops

A Perl script is a file that contains instructions to the perl interpreter, with one instruction per line, that are read one at a time from the top of the script to the bottom. You can, however, divert this flow using a loop. Open a new Perl script loop.pl and write this;

for ($i = 1; $i <= 10; $i = $i + 1)
{
    $five_times_i = 5 * $i;

    print "5 times $i equals $five_times_i\n";
}

What do you think will be printed to the screen? Run the script (perl loop.pl). Did you see what you expected?

This script has introduced a for loop. The loop has five parts;

Loops are very powerful. For example;

for ($i = 0; $i <= 200; $i = $i + 2)
{
    print "$i\n";
}

prints all of the even numbers from 0 to 200.

for ($i = 10; $i > 0; $i = $i - 1)
{
    print "$i...\n";
}

print "We have lift off!\n";

prints out a count down.

for ($i = 1; $i <= 3; $i = $i + 1)
{
    for ($j = 1; $j <= 3; $j = $j + 1)
    {
        $i_times_j = $i * $j;

        print "$i_times_j ";
    }

    print "\n";
}

prints out a 3*3 matrix where the element at (i,j) equals i times j.


Compare with Python


Previous Up Next