Lesson 03 – Loop

Looping is useful when you want to execute a block of code several times.

In Perl, there are four styles of loops.

#!/usr/bin/perl

use strict;
use warnings;

my @pizza = ("plain", "pepperoni", "supreme", "veggie");

foreach (@pizza)
{
    print $_, "\n";
}

When working with arrays, foreach is usually preferred. In the above code, it loops until you reach the end of the array.

In Perl, foreach can be written for.

for (@pizza)
{
    print $_, "\n";
}

$_ is a special kind of variable (the topic variable) that will get an element from the array on each iteration. In the Modern Perl book, the author describes the usage of $_ as similar to the word “it” in the English language.

for (my $i=0; $i<@pizza; $i++)
{
    print $pizza[$i], "\n";
}

The C-style for loop does the same thing but it requires a conditional so that it continues to loop and increment $i by 1 until $i is greater than or equal to the size of the array.

The Perl-style for loop iterating with index over an array is this:

for my $m (0..$#pizza) 
{
     print $pizza[$m], "\n";
}

.. is Perl’s range operator and $#pizza is the highest index.

my $k = 0;

while ($k<@pizza)
{
    print $pizza[$k], "\n";
    $k++;
}

This is the while loop that does exactly the same thing. It loops as long as $k is less than the size of the array.

It will exit the loop when the condition is false.

The until loop is the opposite of the while loop. It will loop and exit when the condition is true.

my $j = 0;

until ($j>=@pizza)
{
    print $pizza[$j], "\n";
    $j++;
}

Notice how @pizza is used instead of scalar(@pizza). That’s because scalar context is implicit there.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>