How to iterate over an array with index using for in Perl?

Question

How to iterate over an array with index using for in Perl?

Iterating Over an Array with Index Using for in Perl

In Perl, arrays are ordered lists accessed by numeric indices starting at zero. Often, when looping over arrays, you need not only the values but also their corresponding indices. Perl offers a few flexible ways to iterate over an array with indices using the for loop.

One common approach is to loop over the range of valid indices and access each element via its index. This method clearly separates indices and values:

#!/usr/bin/perl
use strict;
use warnings;

my @fruits = ('apple', 'banana', 'cherry');

# Iterate over indices from 0 to last index (scalar(@fruits) - 1)
for my $i (0 .. $#fruits) {
    print "Index: $i, Value: $fruits[$i]\n";
}

Explanation

  • @fruits is the array holding our list of fruit names.
  • $#fruits gives the last valid index of the array (length minus one).
  • 0 .. $#fruits is the range operator producing a list of all indices.
  • for my $i ( ... ) { } iterates over each index.
  • Inside the loop, $fruits[$i] accesses the array element at index $i.

This method is explicit and easy to understand, especially for learners. It also avoids any ambiguity related to context or iterating directly over values.

Alternative: Using each for Arrays (Perl 5.12+)

Since Perl 5.12, the each function works on arrays too, returning indices and values one at a time:

use 5.12.0;
my @colors = ('red', 'green', 'blue');

while ( my ($index, $value) = each @colors ) {
    print "Index: $index, Value: $value\n";
}

This is handy but note it is not a for loop and requires Perl 5.12 or newer.

Common Gotchas

  • Using for my $elem (@array) only gives values, no indices.
  • Be careful if the array is empty; 0 .. $#array produces 0 .. -1, which is empty, so the loop won’t run.
  • Perl’s flexibility means there are often multiple ways to do something (TMTOWTDI - "There's More Than One Way To Do It"). Choose the one that improves code readability.

Summary

The most straightforward way to iterate over an array by index using a for loop in Perl is to loop over the numeric range 0 .. $#array, accessing each element inside the loop with the index variable. This technique works reliably in all Perl versions and is easy to understand for beginners.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
STDERR
(empty)

Was this helpful?

Related Questions