Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 43 ยท Control Flow

Loops and Loop Control

Repeat work in Perl with for, foreach, while and until, control loops with last, next, redo and labels, and avoid the do-while trap.

Loops let a program do the same job many times: print every line of a file, add up a list of prices, retry a failed step. Perl has the familiar loops from other languages, plus a few of its own that make common jobs shorter.

This lesson covers the two families (counting loops and condition loops), the keywords that steer them from the inside (last, next, redo), loop labels for nested loops, and one well-known trap with do { } while.

Perl is not installed on this site, so the Perl code below is read-only, and its output comes from a real Perl 5.42 run. The interactive examples are Python stand-ins that mirror the same loop logic.

Pick a loop

foreach Visit every item in a list.
C-style for Count with init, test and step.
while Repeat while a test is true.
until Repeat until a test becomes true.
1 / 2

foreach and for

In Perl, for and foreach are the same keyword. Use whichever reads better. The most common loop visits each item of a list with a loop variable:

PERL
use v5.36;

for my $i (1..3) {
    say "i=$i";
}

my @colors = qw(red green blue);
for my $color (@colors) {
    say "color: $color";
}
TEXT
i=1
i=2
i=3
color: red
color: green
color: blue

1..3 is the range operator, which produces the list 1, 2, 3. Declare the loop variable with my so it exists only inside the loop.

The loop variable is an alias

This detail surprises newcomers. The loop variable is not a copy: it is an alias to the current element. If you change it, you change the array.

PERL
my @words = qw(red green blue);
for my $w (@words) {
    $w = uc $w;
}
say "@words";
TEXT
RED GREEN BLUE

That is handy for in-place edits, but it can cause bugs if you modify the variable by accident. Aliasing is also how @_ works in subroutines (see Subroutines).

The default variable $_

If you leave out the variable, Perl uses $_. Many functions (like print, uc and regex matching) also read $_ by default. A one-line form puts the loop after the statement:

PERL
say "$_" for reverse 1..3;

my @nums = (1..5);
my $sum = 0;
$sum += $_ for @nums;
say $sum;
TEXT
3
2
1
15

This statement-modifier form has no block and no loop variable name, so it suits short jobs. For anything with more than one step, use a normal block with a named variable.

The three-part for

When you need an index with exact control, the C-style loop is available:

PERL
for (my $i = 0; $i < 3; $i++) {
    print $i, " ";
}
print "\n";
TEXT
0 1 2 

It has three parts, separated by semicolons: an initial step, a test checked before each round, and a step after each round. In real Perl code, foreach over a range is much more common, because it cannot have off-by-one mistakes in the test.

Here is the same set of ideas in Python:

Python Stand-in: counting and visiting items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

while and until

A while loop repeats as long as its condition is true, and until repeats until its condition becomes true. Both test before each round, so the body may run zero times.

PERL
my $n = 3;
while ($n > 0) {
    say "n=$n";
    $n--;
}

my $k = 0;
until ($k >= 2) {
    say "k=$k";
    $k++;
}
TEXT
n=3
n=2
n=1
k=0
k=1

The truth rules from Conditionals apply, so while (@queue) loops until the array is empty. The classic Perl idiom for reading input is while (my $line = <$fh>), which stops at the end of the file. You will use it in Reading and Writing Files.

last, next and redo

Three keywords change how the current loop runs. They work in for, foreach, while and until.

  • next skips the rest of this round and starts the next one.
  • last leaves the loop completely (like break in other languages).
  • redo runs the current round again without checking the loop condition or moving to the next item.
PERL
for my $i (1..10) {
    next if $i % 2;      # skip odd numbers
    last if $i > 6;      # stop after 6
    say "even $i";
}
TEXT
even 2
even 4
even 6

redo is rare. It is useful when you need to repeat an item after fixing something, for example after re-reading bad input. Take care, because a redo whose condition never clears is an endless loop.

The next stand-in uses Python's continue and break, which are Perl's next and last. Python has no redo, so the stand-in simulates it with an inner loop.

Python Stand-in: next, last and redo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Labels for nested loops

Inside a loop within a loop, next and last act on the innermost one. To control an outer loop, give it a label (a name in capital letters followed by a colon) and mention the label:

PERL
OUTER: for my $row (1..3) {
    for my $col (1..3) {
        next OUTER if $col > $row;     # abandon the inner loop, go to the next row
        say "row $row, col $col" if $row == $col;
    }
}
TEXT
row 1, col 1
row 2, col 2
row 3, col 3

When the column passes the row number, next OUTER skips straight to the next row. Labels are one of the nicest ways to avoid flag variables like $found.

The do { } while trap

do { ... } while (...) looks like a loop that runs once before testing. It does run at least once:

PERL
my $tries = 0;
do {
    $tries++;
    say "try $tries";
} while ($tries < 3);
TEXT
try 1
try 2
try 3

But there is a catch: do BLOCK is not a real loop block. That means last, next and redo do not work inside it, and Perl will try to leave an enclosing loop instead (or fail with an error if there is none). If you need a "run at least once" loop with an early exit, write a plain loop with its own last:

PERL
while (1) {
    # work happens here
    last if $done;
}

Looping over hashes

Combine for with keys to visit a hash. Sort the keys when you want a stable order:

PERL
my %stock = (apple => 3, banana => 5, cherry => 2);
for my $name (sort keys %stock) {
    say "$name=$stock{$name}";
}
TEXT
apple=3
banana=5
cherry=2

To walk an array with its index at the same time, each on an array returns the index and the value on every call:

PERL
my @letters = qw(x y z);
while (my ($i, $v) = each @letters) {
    say "$i:$v";
}
TEXT
0:x
1:y
2:z

Newer Perls (5.36 and later) can also take two variables at once, as in for my ($key, $value) (%hash). Hashes themselves are covered in Hashes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between for and foreach in Perl?

    for and foreach are synonyms. Either can be used for a list loop or a three-part loop.
  2. 2. What happens if you assign to the loop variable in for my $x (@list) { $x = 0 }?

    The loop variable is an alias to the current element, so assignments change the original array.
  3. 3. Which keyword leaves a loop completely?

    last exits the loop. Perl has no break keyword. next skips to the next round and redo repeats the current one.
  4. 4. How do you skip to the next round of an OUTER loop from inside an inner loop?

    Give the outer loop a label and name it: next OUTER. Without a label, next acts on the innermost loop.
  5. 5. Why should you be careful with do { ... } while (...)?

    do BLOCK is an expression, not a loop, so loop control keywords inside it affect an enclosing loop or fail.

Summary

  • for and foreach are the same; foreach my $x (@list) is the usual loop, and $_ is the default variable.
  • The loop variable is an alias of each element, so changing it changes the array.
  • while repeats while true and until repeats until true; both test before each round.
  • next skips a round, last leaves the loop, redo repeats the round, and labels target outer loops.
  • Avoid last and next inside do { } while, because it is not a real loop.

Next, package your code into reusable pieces in Subroutines.