th206 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Is there a way in Perl to search an array with its value and not by its index? like java does with "IndexOf". Problem is: I have an array of 400 elements. Each element has some number stored. I'm trying to get the index of a particular element. Thanks in advance.

Replies are listed 'Best First'.
Re: Array search
by Cristoforo (Curate) on Jan 28, 2006 at 19:37 UTC
    This will do it
    #!/usr/bin/perl use strict; use warnings; my @array = qw/21 33 5 49 235 40/; my @index = grep {$array[$_] == 235} 0..$#array; print "@index\n";
    (prints 4)
Re: Array search
by jZed (Prior) on Jan 28, 2006 at 20:03 UTC
    Assuming the array elements are unique and that you'll want to find more than one index, a hash is a good solution:
    my @array = qw/a b c d/; my %indexOf = map { $array[$_] => $_} 0..$#array; printf "%s\n", ( $indexOf{c} == 2 ) ? "ok" : "bad";
Re: Array search
by LucaPette (Friar) on Jan 28, 2006 at 19:46 UTC
Re: Array search
by tirwhan (Abbot) on Jan 28, 2006 at 23:11 UTC

    use List::MoreUtils qw(firstidx); my $index = firstidx { $_ == $searchvalue } @array;

    There are ten types of people: those that understand binary and those that don't.