How to get the index of an element in an array?

Does Perl have a build-in function to get the index of an element in an array? Or I need write such a function by myself? [ equivalent to PHP array_search() or JavaScript array.indexOf() ]


use List::Util qw(first);
$idx = first { $array[$_] eq 'whatever' } 0..$#array;

(List::Util is core)


use List::MoreUtils qw(firstidx);
$idx = firstidx { $_ eq 'whatever' } @array;

(List::MoreUtils is on CPAN)

Here's a post-5.10 way to do it, with the added benefit of determining how many indexes match the given value.

my @matches = grep { $array[$_] ~~ $element } 0 .. $#array;

If all elements are guaranteed to be unique, or just the first index is of interest:

my ($index) = grep { $array[$_] ~~ $element } 0 .. $#array;

Here is an autobox solution:

use autobox::Core;

my @things = qw/blue black green red green yellow/;

my $first_green = @things->first_index( sub{ $_[0] eq 'green' } ); # code block
my $last_green  = @things->last_index ( qr/^green$/ );             # or regex

say $first_green;    # => 2
say $last_green;     # => 4

You can write a function for this:

sub array_search {
    my ($arr, $elem) = @_;
    my $idx;
    for my $i (0..$#$arr) {
        if ($arr->[$i] eq $elem) {
            $idx = $i;
    return $idx;            

The index of the first matching element will be returned, or undef.

Need Your Help

Difference between std::merge and std::inplace_merge?

c++ algorithm c++11 stl stl-algorithm

What is the difference between std::merge and std::inplace_merge in terms of complexity and result when it is executed on two consecutive ranges with elements that are all different ? (I am not a n...

Equivalent of Firefox's "error console" in other browsers

javascript browser

Is there an equivalent to Firefox's "Error console" in other browsers? I find the error console handy for finding JavaScript errors, but there doesn't seem to be an equivalent simple way to see error