Foreach Loop
Explore the foreach loop in Perl, a key control structure used to iterate over collections like arrays without relying on indices. Learn its syntax and usage with practical examples to handle elements efficiently. This lesson helps you understand how to process each item in a list, preparing you for more advanced Perl scripting.
We'll cover the following...
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
@arris 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
$xdeclares a variable that will be set to the successive elements of@arrfor each pass through the body. - The
foreachloop 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.
Explanation
In the above code:
- The
foreachstatement 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 $_:
In the next lesson, we’ll discuss the until loop!