Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: Finding index of an entry in an Array

by tuxz0r (Pilgrim)
on Dec 07, 2007 at 03:36 UTC ( [id://655574]=note: print w/replies, xml ) Need Help??


in reply to Re: Finding index of an entry in an Array
in thread Finding index of an entry in an Array

This concept works without List::Util as well,
my @array = qw(dog cat mat bat hat); my ($idx) = grep { $array[$_] eq 'bat' } 0 .. $#array;
Update: Fletch noted an issue, when I was quickly testing on the command line I wasn't assigning to a variable, just printing (e.g. print grep { ... } 0 .. $#array, which evaluates in list context, not scalar context as I through up here with the assignment. Adding the parens clears that up. (Thanks Fletch).

---
s;;:<).>|\;\;_>?\\^0<|=!]=,|{\$/.'>|<?.|/"&?=#!>%\$|#/\$%{};;y;,'} -/:-@[-`{-};,'}`-{/" -;;s;;$_;see;
Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

Replies are listed 'Best First'.
Re^3: Finding index of an entry in an Array
by Fletch (Bishop) on Dec 07, 2007 at 03:45 UTC

    Not without parens (since grep in scalar context returns the number of matching elements) and not without searching the entire list of indexen (which of course could be what the OP really wants, the indexen of all matching elements).

    my( $idx ) = grep { $array[ $_ ] eq 'bar' ) 0..$#array; my @indexen = grep { $array[ $_ ] eq 'bar' } 0..$#array;

    That aside, yup that's another way to do it. :)

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found