Loops

Loops are blocks that are evaluated several times. They are usually used for repetitive actions, walking through the data structure etc.

For/Foreach

Foreach loop is usually used for looping through the list or array. For example:

foreach my $element (1, 2, 3, 4, 5) {
    say $element;
}

You can pass an array of course:

my @array = (1 .. 5);
foreach my $element (@array) {
    say $element;
}

As you can see we create a special $element variable that is aliased to every array element on every iteration. Beware that by changing the $element value you change the actual value in the array:

my @array = (1 .. 5);
foreach my $element (@array) {
    $element *= 2;
}

foreach my $element (@array) {
    say $element;
}

Exercise

Print only the even values from 0 to 10:

foreach my $element (...) {
    if (...) {
        ...
    }
}

While

While is a more advanced loop that iterates while the expression is true.

my $i = 10;
while ($i > 0) {
    say $i;

    $i = $i - 1;
}

As soon as expression $i > 0 becomes false the loop stops.

Exercise

Print only the odd values from 0 to 10:

my $i = ;
while ($i ...) {
    if (...) {
        ...
    }
}

Getting out of the loop

Often you want to terminate the loop without waiting until it finishes. You usually use the last keyword:

my $i = 0;
while ($i < 100) {
    last if $i == 10;

    say $i;

    $i = $i + 1;
}

This loop will not iterate 100 times because we terminate it when $i is 10.