Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Finding the index of a specific element in an array.

by Thakur (Acolyte)
on Jan 24, 2012 at 20:52 UTC ( #949757=perlquestion: print w/replies, xml ) Need Help??
Thakur has asked for the wisdom of the Perl Monks concerning the following question:

How can I find the index of a specific element in an array.

For eg.

my @array = (2,4,7,5,8);

How can I get the index of the element 7

  • Comment on Finding the index of a specific element in an array.

Replies are listed 'Best First'.
Re: Finding the index of a specific element in an array.
by BrowserUk (Pope) on Jan 24, 2012 at 21:15 UTC

    On the most recent perl's you can use each:

    my @array = (2,4,7,5,8);; my($i, $v ) = each @array until $v == 7;; print $i;; 2

    On older perl's:

    my @array = (2,4,7,5,8);; my $i = 0;; ++$i until $array[ $i ] == 7;; print $i;; 2

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re: Finding the index of a specific element in an array.
by toolic (Bishop) on Jan 24, 2012 at 21:08 UTC
    One way is to use List::MoreUtils:
    use warnings; use strict; use List::MoreUtils qw(firstidx); my @array = (2,4,7,5,8); printf "item with index %i in list is 7\n", firstidx { $_ == 7 } @arra +y; __END__ item with index 2 in list is 7
Re: Finding the index of a specific element in an array.
by Marshall (Abbot) on Jan 24, 2012 at 21:09 UTC
    There are many ways to write this code. One of those ways is with grep. You could make a foreach loop to do the same thing.
    #!/usr/bin/perl -w use strict; my @array = (2,4,7,5,8); # grep would return indicies of all 7's # here, just the first one is all we keep track of my ($first_seven) = grep{$array[$_] == 7}(0..@array-1); print $first_seven; # prints 2
Re: Finding the index of a specific element in an array.
by GrandFather (Sage) on Jan 24, 2012 at 21:22 UTC

    Why? Maybe there is a better way of representing the data so you don't need to search an array to get whatever answer you need?

    True laziness is hard work
Re: Finding the index of a specific element in an array.
by i5513 (Pilgrim) on Jan 24, 2012 at 23:28 UTC

    Using regex features, maybe a good homework task:

    use strict; use warnings; my @a=(2,4,7,5,8); my ($position, $spaces); # Elements have not " " ("@a" concatenate with spaces) if ("@a" =~ /(?:^|\ ) # Element searched maybe the first or not \K # Count previous group matched within ${^PREMATCH} var (?{ $position=pos; $spaces= () = ${^PREMATCH} =~ m, ,g; }) # Next group will be that which are we searching, s +o # we take note about where is it and how many space +s # should we ignore ("@a" add spaces) (8) # Element searched (?:\ |$) # Element searched maybe the last or not /xpg) { print "Position:" ,$position - $spaces, "\n"; }

    In your example you can use index function:

    my $pos=index (join ("",@array),7);
Re: Finding the index of a specific element in an array.
by Anonymous Monk on Jan 24, 2012 at 21:14 UTC

    Iterate over the array ( foreach ) and compare

    http://perldoc.perl.org/perlintro.html#for

    #!/usr/bin/perl -- use strict; use warnings; use Data::Dumper; my @array = ( 2,4,7,5,8); my( @index7s ) = grep { 7 == $array[$_] } 0 .. $#array; print Dumper( \@array, \@index7s, [ @array[@index7s] ] ); __END__ $VAR1 = [ 2, 4, 7, 5, 8 ]; $VAR2 = [ 2 ]; $VAR3 = [ 7 ];
Re: Finding the index of a specific element in an array.
by JavaFan (Canon) on Jan 24, 2012 at 21:16 UTC
    for (my $i = 0; $i < @array; $i++) { if ($array[$i] == 7) { say "The index is $i"; last; } }
    Hey! A "C-style" for loop. I guess it contains an off-by-one error.
      I guess it contains an off-by-one error.

      No, but it does contain synthetic code.

        No, but it does contain synthetic code.
        Yeah, and? Care to show us some 'natural' code which actually describes and solves the problem in hand and that doesn't have any an artifact of the particular method that you have chosen to solve the problem.? The emphasis are verbatim quotes from the article you link to.
Re: Finding the index of a specific element in an array.
by mbethke (Hermit) on Jan 25, 2012 at 07:24 UTC

    Although it doesn't make a lot of sense to discuss Perl solutions when the first comment suggests one that's unlikely to be beaten in efficiency, just for the TIMTOWTDI of it here's another slow one:

    $pos = do{ my @h{reverse @a} = (reverse 0..$#a); $h{$elem}};

    If it doesn't matter when duplicate elements are found in their last instead of first position, you can omit the reverse.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://949757]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2018-08-16 17:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:









    Results (169 votes). Check out past polls.

    Notices?