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: @fruits is an array variable, $fruit is a scalar variable holding one element at a time.
  • foreach loop: Iterates over each element in the array.
  • Variable declaration: Using my creates 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 for instead of foreach; in Perl they are synonyms.

Common Pitfalls

  • Modifying the loop variable: Changing $fruit inside the loop does not modify the original array elements unless you iterate over references or indices.
  • Variable scoping: Using my inside the loop prevents unexpected side effects elsewhere in your code.
  • Loops over empty arrays: foreach simply 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 say function (with use feature 'say';) to print with an automatic newline, but print + \n remains 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions