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
@fruitsis the array we're searching.$targetis the element we're looking for.0..$#fruitsgenerates a list of indices for the array.grep { CONDITION } LISTfilters the list to indices where the element matches.- If
@indicesis non-empty, the first match is$indices[0].
Perl Concepts Involved
- Sigil $ and @:
$fruits[$_]accesses a scalar element in the array. - Array indices:
$#arraygives the highest index, so0..$#arraycovers all indices. - Context: Using
grepin list context returns all matching indices. - TMTOWTDI (There’s More Than One Way To Do It): You could write this with explicit loops,
List::MoreUtilsmodules, or customized subroutines.
Common Gotchas
- Comparisons with
eqwork 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
@indicesas-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
(empty)(empty)