How to iterate over an array with foreach in Perl?
Question
How to iterate over an array with foreach in Perl?
Iterating Over an Array with foreach in Perl
In Perl, one of the most common tasks when working with arrays is iterating over their elements. The foreach loop provides a simple and readable way to loop through each element of an array in sequence.
Perl arrays are denoted by the sigil @ (e.g., @array), and individual elements are accessed using the scalar sigil $ (e.g., $array[0]). The foreach loop allows you to assign each element, one by one, to a lexical variable, which you can then manipulate or print.
Basic Syntax
foreach my $element (@array) {
# do something with $element
}
Here, $element is a lexical variable representing the current value from @array.
Runnable Example
The following Perl script demonstrates iterating over an array of fruit names using foreach and printing each element to STDOUT:
#!/usr/bin/perl
use strict;
use warnings;
my @fruits = ('apple', 'banana', 'cherry', 'date');
foreach my $fruit (@fruits) {
print "I like $fruit\n";
}
When you run this script, the output will be:
I like apple I like banana I like cherry I like date
Explanation and Perl Concepts
- Sigils:
@fruitsis an array variable,$fruitis a scalar variable holding one element at a time. foreachloop: Iterates over each element in the array.- Variable declaration: Using
mycreates a lexical variable scoped only to the loop block. - Context: The array is iterated in list context, delivering one element for each iteration.
- TMTOWTDI: You can also write
forinstead offoreach; in Perl they are synonyms.
Common Pitfalls
- Modifying the loop variable: Changing
$fruitinside the loop does not modify the original array elements unless you iterate over references or indices. - Variable scoping: Using
myinside the loop prevents unexpected side effects elsewhere in your code. - Loops over empty arrays:
foreachsimply does nothing if the array is empty, which is usually safe but good to keep in mind for logic.
Additional Tips
- You can iterate over array indices using
for my $i (0 .. $#array)if you need to modify original elements. - Since Perl 5.10, you can use the
sayfunction (withuse feature 'say';) to print with an automatic newline, butprint+\nremains universal.
Using foreach is the cleanest and most idiomatic way to access each element of an array sequentially in Perl, making your code easy to read and maintain.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 5ms
(empty)(empty)