Perl Loops Guide — while, for, foreach, and Iteration Control
In this tutorial, you will learn about Perl Loops Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Perl loops cover while (repeat while true), until (repeat while false), for (C-style three-expression), and foreach (list iteration) -- with next (skip to next), last (exit loop), and redo (repeat iteration) for precise flow control.
while Loop
my $i = 1;
while ($i <= 5) {
print "$i\n";
$i++;
}
until Loop
my $count = 0;
until ($count >= 3) {
print "Attempt $count\n";
$count++;
}
# Body executes while condition is false
for Loop (C-style)
for (my $i = 0; $i < 5; $i++) {
print "$i\n";
}
# Optional all parts
my $j = 0;
for (; $j < 5; ) {
print "$j\n";
$j++;
}
foreach Loop
my @items = qw(apple banana cherry);
foreach my $item (@items) {
print "$item\n";
}
# $_ as default iterator
foreach (@items) {
print "$_\n";
}
# for is alias for foreach
for my $item (@items) {
print "$item\n";
}
Loop Control
foreach my $num (1..10) {
next if $num % 2 == 0; # skip even numbers
last if $num > 7; # exit after 7
print "$num "; # 1 3 5 7
}
# redo restarts the current iteration
my $tries = 0;
while ($tries < 3) {
$tries++;
my $input = <STDIN>;
chomp $input;
redo unless $input =~ /^\d+$/; # ask again if not number
}
Common Mistakes
1. Infinite loops
Forgetting to update the loop variable: while ($i < 10) { print $i } without $i++.
2. Modifying array during foreach
foreach aliases the loop variable to the actual element. Modifying $_ changes the original array.
3. Confusing next and last
next skips to the next iteration (like continue). last exits the loop entirely (like break).
Practice Questions
1. What is the difference between next and last? next skips the rest of the current iteration and moves to the next. last exits the loop entirely.
2. How do you iterate over a list with foreach?
foreach my $element (@list) { ... }. $_ is the default if no variable is specified.
3. What does redo do? redo restarts the current iteration without re-evaluating the condition.
FAQ
{{< faq question="Is there a do-while loop in Perl?" >}}
Yes: do { ... } while (condition). The body executes at least once before the condition is checked.
{{< /faq >}}
{{< faq question="Can I loop over a hash?" >}}
Use foreach my $key (keys %hash) { my $value = $hash{$key}; ... } or while (my ($k, $v) = each %hash) { ... }.
{{< /faq >}}
{{< faq question="What is the default variable $?" >}} $ is the default input and pattern matching space. Many Perl operations use $_ when no variable is specified. {{< /faq >}}
What's Next
Now learn about I/O operators in Perl.
| Topic | Description | Link |
|---|---|---|
| I/O Operators | readline, read, sysread | {{< ref "11-io-operators" >}} |
| References | Scalar, array, hash references | {{< ref "12-references" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro