For in Perl
Perl offers several ways to create loops. Here are some basic types of loops in Perl.
When you run this Perl script, you’ll get:
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.