HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to PerlOperatorsStringsArrays (@)Hashes (%)Conditions (if)LoopsFunctions (sub)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
✍️ Text & Number
📋 Array & Hash
🔁 Condition & Loop
🧩 Function (sub)
Perl›Loops

Loops

Iterating over items/ranges with foreach and conditional repetition with while.

Simple enough for a 5-year-old to understand

foreach

Example code
1
foreach my $i (1..3) {
(1..3) generates a range.
Loop(1..3) generates a range.
2
print "$i\n";
3
}
Loop
💡 Hint: (1..5) generates a range from 1 to 5 (both inclusive).

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using foreach.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

Loops in Perl are written with for, foreach, while, and until. foreach iterates over a list; for can be used both as a C-style counter loop and interchangeably with foreach—Perl considers the two synonymous.

A feature of Perl is the default variable: if you don't write a variable name in a foreach loop, each element is assigned to a special variable, and many functions use this variable when no arguments are given. It is very practical in short scripts.

An important and lesser-known behavior: the variable in a foreach loop is an alias to the list element, not a copy. If you modify it inside the loop, the original array also changes. When used consciously, this is powerful; when unaware, it's a source of bugs.

What you will learn

  • Using foreach and counter-based for
  • The difference between while and until
  • Loop control commands
  • The default variable
  • Alias behavior

Who is this for?

  • Script writers who will process lists
  • Those looking for break and continue
  • Those who accidentally modify the array in a loop

When to use?

When processing file lines or command output, foreach is the most natural format.

while is used in tasks requiring an indeterminate number of repetitions, such as scripts waiting until a condition is met.

Common mistakes

Wrong

my @liste = (1, 2, 3);
foreach my $x (@liste) {
  if ($x == 2) { break; }
  print "$x\n";
}

To exit a loop in Perl, last is used instead of break; break is not a defined command and causes a syntax error. Similarly, next is used instead of continue to move to the next step. Name differences constantly confuse those coming from other languages.

Correct

my @liste = (1, 2, 3);
foreach my $x (@liste) {
  if ($x == 2) { last; }
  print "$x\n";
}

Wrong

my @liste = (1, 2, 3);
foreach my $x (@liste) {
  $x = $x * 2;
}
print "@liste\n";

There is no error here, but the result might be surprising: since the loop variable is an alias of the element, the array itself changed and doubled values were printed to the screen. If you think you are working on a copy, this behavior produces unexpected results.

Correct

my @liste = (1, 2, 3);
my @yeni = map { $_ * 2 } @liste;
print "@yeni\n";

Wrong

my $i = 1;
while ($i <= 5) {
  print "$i\n";
}

Since the counter is not incremented, the condition remains true forever and the script never ends. You have to ensure progress in while loops; if the number of repetitions is known, using foreach eliminates this risk.

Correct

my $i = 1;
while ($i <= 5) {
  print "$i\n";
  $i++;
}

Frequently asked questions

What is the difference between last and next?

last completely terminates the loop; next only skips that step and moves to the next one. A third command, redo, repeats the same step without re-evaluating the condition and is rarely used.

What does the default variable do?

When you don't write a loop variable, each element is assigned to it, and many functions use it when called without arguments. In one-liner scripts it shortens the code a lot, but in long code it decreases readability; giving explicit names is generally better.

How do I iterate over array indices?

You use the range operator together with the special variable that gives the last index. If you don't really need the index, iterating directly over the elements is both shorter and eliminates the risk of out-of-bounds errors.

Summary

last is used to exit the loop, and next is used to skip.

The foreach variable is an alias of the element.

You must ensure progress in a while loop.

for and foreach are synonymous.

The default variable is useful in short scripts.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code