How to use foreach loop to iterate over arrays in Perl?
Question
How to use foreach loop to iterate over arrays in Perl?
In Perl, the foreach loop (also aliased as for) is the most common and convenient way to iterate over elements of an array. It lets you process each element one by one without manually managing indexes. This makes your code clearer, shorter, and less error-prone.
Basic syntax of foreach
The syntax looks like this:
foreach my $element (@array) {
# do something with $element
}
Here, @array is the array you want to loop over, and $element is a scalar variable that takes on the value of each element in turn. Inside the loop block, you can use $element just like any other scalar.
Key concepts in Perl foreach loops
- Sigils: Notice how
@arrayhas the "array" sigil@. When used inforeach, it expands to the list of elements. The loop variable is scalar ($element) because each item is one scalar at a time. - Aliases: The loop variable (
$element) is an alias to the actual array element. Modifying$elementinside the loop changes the original array value. - TMTOWTDI: Perl is flexible; you can use either
foreachor justforas a loop keyword—they work the same for list iteration. - Context: The loop iterates in list context over the array, so all elements are visited in order.
Example: Iterating over an array and printing each element
use strict;
use warnings;
my @languages = ('Perl', 'Python', 'Ruby', 'JavaScript');
foreach my $lang (@languages) {
print "I like $lang\n";
}
Running this will output:
I like Perl
I like Python
I like Ruby
I like JavaScript
Modifying elements in a foreach loop
Because the loop variable aliases the original element, you can modify the array in-place:
foreach my $lang (@languages) {
$lang = uc($lang); # convert to uppercase
}
print join(", ", @languages), "\n"; # prints: PERL, PYTHON, RUBY, JAVASCRIPT
Common pitfalls
- Using a
foreachloop variable withoutmycan cause issues with variable scope, especially in strict mode. - Modifying the array size inside the loop is not recommended—it may lead to unexpected behavior.
- If you want to iterate by index instead, you can use a C-style
forloop with indexes, butforeachis preferred for direct element access.
Summary
The foreach loop is an easy and expressive way to iterate over arrays in Perl. Remember the signature:
foreach my $element (@array) {
# use $element here
}
This loop variable aliases the current element, and you can read or modify it. Whether you're printing elements, transforming them, or processing data, foreach offers a clean syntax aligned with Perl’s flexible philosophy.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 6ms
(empty)(empty)