Foreach Loop
Let's discuss the foreach loop and its implementation in Perl.
We'll cover the following...
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!