AnyCompiler

Loops and foreach

Perl has a C-style for loop with the familiar three-part header, plus last (break out of the loop entirely) and next (skip straight to the next iteration) to control it mid-flight.

use strict;
use warnings;

for (my $i = 0; $i < 5; $i++) {
    next if $i == 2;
    last if $i == 4;
    print "i=$i\n";
}
Output
i=0
i=1
i=3

i=2 is skipped by next (next still runs the $i++ increment before re-checking the condition), and the loop stops entirely once last fires at i=4 — i=4 itself is never printed. More idiomatic for iterating a list is foreach (or its shorter alias, for) with my $x (@list), which needs no index variable at all:

use strict;
use warnings;

my @colors = ("red", "green", "blue");
foreach my $color (@colors) {
    print "Color: $color\n";
}

for my $n (1..5) {
    print "N: $n\n";
}
Output
Color: red
Color: green
Color: blue
N: 1
N: 2
N: 3
N: 4
N: 5

1..5 is a range — Perl expands it into the list (1, 2, 3, 4, 5). foreach and for are genuinely the same keyword in Perl; which one you use is purely a style choice. Next: hashes — Perl's key-value collection.

Practice exercise

Sum the numbers 1 through 10 using foreach my $n (1..10), then print the sum.