In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now it’s time to look at one of the most powerful features in any programming language: loops! Loops allow you to execute a block of code multiple times, making it easy to process lists, repeat actions, and automate repetitive tasks.
Most programming languages have similar constructs for loop control flow statements, and Perl is no exception. In this post, we will cover the basic types of loops in Perl: 'for', 'foreach', 'while' and 'until.
You would use a loop in your code when you would like to repeat a block of code multiple times, such as iterating over an array or performing an action until a condition is met.
You can use the following table as a reference for loops in Perl:
Loop Type | Syntax Example | Description |
---|---|---|
for | for (my $i = 0; $i < 10; $i++) { ... } | Traditional C-style loop with init, test, update |
for | for my $item (@array) { ... } | Iterates over each element in a list or array |
foreach | foreach my $item (@array) { ... } | Iterates over each element in a list or array |
while | while (condition) { ... } | Repeats block while condition is true |
until | until (condition) { ... } | Repeats block until condition is true |
do...while | do { ... } while (condition); | Executes block at least once, then repeats |
Today we will explore these loop types in more detail, with examples to illustrate their use. We will create a simple Perl script that demonstrates each type of loop, and we will also discuss when to use each type.
Firstly, the 'for' loop is a traditional loop that allows you to specify an initialisation, a condition, and an increment. It is useful when you know the number of iterations in advance.
Here’s an example of a c style 'for' loop that prints numbers from 0 to 9:
#!/usr/bin/perl
use strict;
use warnings;
for (my $i = 0; $i < 10; $i++) {
print "Number: $i\n";
}
This loop initialises '$i' to 0, checks if '$i' is less than 10, and increments '$i' by 1 after each iteration. The loop will print the numbers from 0 to 9.
If you run the code you will get the following output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
The 'for' loop is versatile and can also be used to iterate over arrays or lists. Here’s an example of a 'for' loop that iterates over an array of numbers accessing by index:
my @numbers = (1, 2, 3, 4, 5);
for my $i (0 .. $#numbers) {
print "Number: $numbers[$i]\n";
}
This loop uses the range operator '..' to create a list of indices from 0 to the last index of the '@numbers' array ('$#numbers'). It then prints each number in the array.
It will extend your output to include:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
You can also write this code like:
for my $num (@numbers) {
print "Number: $num\n";
}
Or you can one line the 'for' loop to iterate over an array directly, which is often more concise if you only need to perform one task during iteration:
print "Number: $_\n" for @numbers;
This one-liner uses the default variable '$_' to refer to each element in the '@numbers' array, printing each number in a single line. This will produce the same output as before, but in a more compact form.
Next, we have the 'foreach' loop, which is specifically designed to iterate over lists or arrays more efficiently. It is a more readable way to process each element in an array without needing to manage an index variable. Here’s an example of a 'foreach' loop:
my @fruits = ('apple', 'banana', 'cherry');
foreach my $fruit (@fruits) {
print "Fruit: $fruit\n";
}
This loop goes through each element in the '@fruits' array and prints it. The 'foreach' loop is often preferred for its clarity when dealing with arrays.
If you run the code you will get the following extended output:
Fruit: apple
Fruit: banana
Fruit: cherry
The 'while' loop is another common type of loop that continues to execute as long as a specified condition is true. It is useful when the number of iterations is not known beforehand and depends on some dynamic condition.
Here’s an example of a 'while' loop that prints numbers from 0 to 9 again:
my $i = 0;
while ($i < 10) {
print "Number: $i\n";
$i++;
}
This loop initializes '$i' to 0 and continues to print the value of '$i' until it reaches 10, incrementing '$i' by 1 in each iteration.
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
The 'until' loop is rarely used but serves a similar purpose to the 'while' loop. It continues to execute as long as the specified condition is false. This can be useful when you want to repeat an action until a certain condition is met.
Here’s an example of an 'until' loop that prints numbers from 0 to 9:
$i = 0;
until ($i >= 10) {
print "Number: $i\n";
$i++;
}
This loop will print the value of '$i' until it is greater than or equal to 10, effectively achieving the same result as the 'while' loop example.
This will produce the same output as the 'while' loop, but it reads more naturally in some contexts where you want to express "until" a condition is met.
Finally, we have the 'do...while' loop, which is similar to the 'while' loop but guarantees that the block of code will be executed at least once before checking the condition. This can be useful when you want to ensure that an action is performed before any condition is evaluated. Here’s an example of a 'do...while' loop that prints numbers from 0 to 9:
#!/usr/bin/perl
use strict;
use warnings;
my $i = 0;
do {
print "Number: $i\n";
$i++;
} while ($i < 10);
This loop will print the value of '$i' and then check if it is less than 10. It will continue to execute until '$i' reaches 10.
In summary loops are essential for automating repetitive tasks and processing collections of data. By mastering these constructs, you can write more efficient and readable Perl scripts. Each loop type serves a specific purpose and can be used effectively depending on the situation, we will learn more when in particular to use a while loop in the future. Next time we will look at scalars in more detail.