Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Array search

by th206 (Initiate)
on Jan 28, 2006 at 19:21 UTC ( #526195=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://526195]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2022-05-26 09:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (93 votes). Check out past polls.

    Notices?