For in Perl

Perl offers several ways to create loops. Here are some basic types of loops in Perl.

use strict;
use warnings;

# The most basic type, with a single condition.
my $i = 1;
while ($i <= 3) {
    print "$i\n";
    $i = $i + 1;
}

# A classic C-style for loop.
for (my $j = 0; $j < 3; $j++) {
    print "$j\n";
}

# Another way of accomplishing the basic "do this N times" iteration
# is to use a foreach loop with a range.
foreach my $i (0..2) {
    print "range $i\n";
}

# Perl's infinite loop, which will continue until you 'last' out of 
# the loop or 'return' from the enclosing subroutine.
while (1) {
    print "loop\n";
    last;
}

# You can also 'next' to the next iteration of the loop.
foreach my $n (0..5) {
    next if $n % 2 == 0;
    print "$n\n";
}

When you run this Perl script, you’ll get:

$ perl for.pl
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Perl, the while loop is often used for condition-based looping, similar to the first example in the original code. The C-style for loop is directly supported in Perl as well.

The foreach loop in Perl is very versatile and can be used to iterate over arrays or ranges, similar to the range functionality in the original example.

Perl’s while (1) construct creates an infinite loop, which can be exited using last (equivalent to break) or return.

The next keyword in Perl is equivalent to continue in many other languages, allowing you to skip to the next iteration of the loop.

We’ll see some other loop forms later when we look at iterating over arrays, hashes, and other data structures.