Foreach Loop

Let's discuss the foreach loop and its implementation in Perl.

Introduction

The foreach statement is similar to the for statement, as both are the iterative statements. However, the foreach statement lacks an iteration index and works even with collections that lack indices altogether.

Syntax

The foreach statement is written in the following form:

Explanation

  • The @arr is the collection (a set of similar or different objects) in which the iteration will happen. It can be an array or a list (an ordered collection of scalar values).
  • The $x declares a variable that will be set to the successive elements of @arr for each pass through the body.
  • The foreach loop exits when there are no more elements in the collection.

We’ll discuss arrays in detail in the coming chapters.

Example

Let’s take a look at an example using the foreach loop.

Press + to interact
@itemsToWrite = ('Alpha', 'Bravo', 'Charlie'); #an array of strings
foreach $item(@itemsToWrite){ #iterating through each element of array itemsToWrite
print "$item\n"; #displaying each element of array in console
}

Explanation

In the above code:

  • The foreach statement iterates over the elements of the array containing strings to write “Alpha”, “Bravo”, and “Charlie” to the console.

We can also do the same in the following way, by removing the variable and accessing the items of the array using $_:

Press + to interact
@itemsToWrite = ('Alpha', 'Bravo', 'Charlie'); #an array of strings
foreach (@itemsToWrite){ #iterating through each element of array itemsToWrite
print "$_\n"; #displaying each element of array in console
}

In the next lesson, we’ll discuss the until loop!