Learning Perl - Loops and Iteration


Learning Perl - Loops and Iteration


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";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You can also write this code like:

for my $num (@numbers) {
    print "Number: $num\n";
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Variables
I will attempt to explain things in this post in a way that is easy to understand, even for those who...
Learning Perl - Arrays
As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Conditional Statements
So far we have covered basic variables in Perl, today we are going to look at how to use these...
Learning Perl - Scalars
Before moving onto more complex topics lets come back to how we represent data in Perl. The most...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - Modules
A module in Perl is a reusable piece of code that can be included in your scripts to provide...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...