Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Finding index of an entry in an Array

by Fletch (Chancellor)
on Dec 07, 2007 at 03:20 UTC ( #655573=note: print w/replies, xml ) Need Help??

in reply to Finding index of an entry in an Array

Aside from the fact that the index of 'bar' in your sample array is 1 not 2 (remember array indexen start at 0) . . .

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

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

Replies are listed 'Best First'.
Re^2: Finding index of an entry in an Array
by snoopy (Deacon) on Dec 07, 2007 at 03:48 UTC
    Also, List::MoreUtils has a first_index method:
    use List::MoreUtils; my $input = 'qux'; my @repo = qw (foo bar qux); Print List::MoreUtils::first_index {$_ eq $input} @repo;
Re^2: Finding index of an entry in an Array
by tuxz0r (Pilgrim) on Dec 07, 2007 at 03:36 UTC
    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.

      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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://655573]
[Corion]: Meh. My lack of embedded Pg is showing. I can get the data for an image gallery with one SQL statement, but not with SQLite as it doesn't do window functions :-(
[Corion]: Hmmm. Maybe I can still fake the one spot where I want/need a window function in SQLite... I think I'm never really interested in the real "next" image (not hidden/deleted)

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2018-03-23 17:47 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (295 votes). Check out past polls.