Loops
Master repetition in Perl with for, foreach, while, until, postfix loop modifiers, and the last/next control keywords.
Introduction
Loops let a program repeat a block of code, either a fixed number of times or until a condition changes. Perl supports every common loop style you would expect from a C-family language — while, until, a C-style for, and a list-oriented foreach — plus its own compact postfix syntax for short loops.
By the end of this lesson you will be able to choose the right loop for the job, and control loop execution precisely using last (Perl's equivalent of break) and next (Perl's equivalent of continue).
- How while and until loops work.
- How to use the classic C-style for loop.
- How foreach iterates cleanly over lists and arrays.
- How last and next control loop flow.
The while Loop
A while loop keeps running its block as long as its condition stays true. It checks the condition before every iteration, so if the condition starts out false, the loop body never runs at all.
use strict;use warnings;
my $count = 1;
while ($count <= 5) { print "Count: $count\n"; $count++;}Click Run to see what this code prints.
The until Loop
until is the inverse of while: it keeps looping as long as the condition is false, and stops once it becomes true. Like unless, it exists mainly to make certain conditions read more naturally.
use strict;use warnings;
my $tickets = 3;
until ($tickets == 0) { print "Selling ticket, $tickets left.\n"; $tickets--;}print "Sold out!\n";Click Run to see what this code prints.
The C-Style for Loop
Perl supports the traditional three-part for loop familiar from C, Java, and JavaScript: an initializer, a condition, and an increment expression, each separated by semicolons.
use strict;use warnings;
for (my $i = 0; $i < 5; $i++) { print "Iteration $i\n";}Click Run to see what this code prints.
Declaring my $i inside the for(...) parentheses scopes $i to the loop itself — it does not leak into the surrounding code, which is good practice and avoids accidental reuse bugs.
The foreach Loop
foreach (often just written as for — they are interchangeable keywords in Perl) iterates directly over a list or array, assigning each element in turn to a loop variable. This is the loop you will reach for most often when working with arrays.
use strict;use warnings;
my @fruits = ('apple', 'banana', 'cherry');
foreach my $fruit (@fruits) { print "I like $fruit\n";}Click Run to see what this code prints.
If you omit the loop variable entirely, Perl uses the special default variable $_ to hold each element, which pairs nicely with functions like print that also default to operating on $_.
use strict;use warnings;
my @numbers = (1, 2, 3);
foreach (@numbers) { print "$_ squared is ", $_ * $_, "\n";}Click Run to see what this code prints.
Postfix Loop Modifiers
Just like conditionals, Perl allows while and foreach (usually written as for in this position) to be used as statement modifiers for compact one-line loops.
use strict;use warnings;
my @colors = ('red', 'green', 'blue');
print "$_\n" for @colors;
my $n = 3;print "$n... " and $n-- while $n > 0;print "liftoff!\n";Click Run to see what this code prints.
last and next
Inside any loop, last immediately exits the loop entirely (equivalent to break in C-family languages), while next skips the rest of the current iteration and moves on to the next one (equivalent to continue).
use strict;use warnings;
foreach my $num (1..10) { next if $num % 2 == 0; # skip even numbers last if $num > 7; # stop once we pass 7 print "Odd number: $num\n";}Click Run to see what this code prints.
Both last and next can also target labeled outer loops (LOOP: while (...) { ... last LOOP; ... }), which is useful for breaking out of nested loops in one step — something many languages need a separate flag variable to accomplish.
Common Mistakes
- Forgetting to increment the loop counter in a while loop, causing an infinite loop.
- Using last when next was intended (or vice versa), which either exits too early or skips the wrong iteration.
- Modifying an array while iterating over it with foreach, which can produce unpredictable results.
- Confusing $_ across nested foreach loops without an explicit loop variable name.
- Writing for (;;) { ... } for an intentional infinite loop and forgetting a last condition inside it.
Best Practices
- Prefer foreach over a manual C-style for loop whenever you are iterating over a known list or array.
- Give loop variables descriptive names (my $line, my $user) rather than relying on $_ except in short one-liners.
- Use next as an early "skip" guard clause to avoid deeply nested if blocks inside loops.
- Label loops explicitly when nesting more than two levels deep, so last/next targets are unambiguous.
- Always scope loop counters with my to avoid leaking variables into the surrounding code.
Frequently Asked Questions
They are actually the same keyword under the hood — for can be used both in the classic C-style three-part form and in the list-iteration form that foreach uses. Most Perl style guides use foreach for list iteration to make the intent clear.
Yes: do { ... } while (condition); runs the block at least once before checking the condition, just like in C and Java.
Use a range in a foreach, like foreach my $i (1..10) { ... }, which is idiomatic Perl for a fixed-count loop.
Yes, using a loop label: OUTER: foreach my $x (...) { foreach my $y (...) { last OUTER if $condition; } }
Key Takeaways
- while and until repeat based on a condition checked before each iteration.
- The C-style for loop gives full control over initialization, condition, and increment.
- foreach is the idiomatic way to iterate over arrays and lists, and defaults to $_ if no variable is given.
- Postfix loop modifiers offer a compact one-line syntax for simple repetition.
- last exits a loop entirely; next skips to the following iteration.
Summary
Loops are how Perl programs repeat work, whether that is processing every line of a file or every element of an array. With conditionals and loops both under your belt, you are ready to dig into one of Perl's greatest strengths: string manipulation.