data-structures intermediate

How to find the index of an element in an array in Perl?

Question

How to find the index of an element in an array in Perl?

In Perl, unlike some other languages, there is no built-in function that directly returns the index of an element in an array. However, you can find the index by searching the array element-by-element using a loop or using the powerful grep function in scalar context.

Basic Concept: Using a Loop to Find Index

The most straightforward method is to iterate over the array, checking each element against the target value. When a match is found, you can return the index.

Using grep to Find the Index

The grep function tests each element against a condition and returns all elements matching it. In scalar context, it returns the count of matches. But, while grep normally returns the matched elements, it can also return their indices by using the index in the block:


my @matches = grep { $arr[$_] eq $target } 0..$#arr;

This returns all indices where the element equals the target. Usually, you want just the first occurrence, so you take the first element of that list.

Full Example: Get Index of the First Matching Element


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

my @fruits = qw(apple banana cherry banana date);
my $target = "banana";

# Find all indices where fruit matches target
my @indices = grep { $fruits[$_] eq $target } 0 .. $#fruits;

if (@indices) {
    print "The first index of '$target' is $indices[0]\n";
} else {
    print "'$target' not found in the array.\n";
}

Explanation

  • @fruits is the array we're searching.
  • $target is the element we're looking for.
  • 0..$#fruits generates a list of indices for the array.
  • grep { CONDITION } LIST filters the list to indices where the element matches.
  • If @indices is non-empty, the first match is $indices[0].

Perl Concepts Involved

  • Sigil $ and @: $fruits[$_] accesses a scalar element in the array.
  • Array indices: $#array gives the highest index, so 0..$#array covers all indices.
  • Context: Using grep in list context returns all matching indices.
  • TMTOWTDI (There’s More Than One Way To Do It): You could write this with explicit loops, List::MoreUtils modules, or customized subroutines.

Common Gotchas

  • Comparisons with eq work for string comparison; use == for numbers.
  • If the element doesn't exist, you get an empty list; always check before using the index.
  • This approach finds the first match; to find all indices, use @indices as-is.
  • Perl arrays are zero-based, so the index starts at 0.

This method works reliably on Perl 5 and above without external modules.

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