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

Re: how do i find the index of a specific array value?

by merlyn (Sage)
on Apr 26, 2001 at 03:47 UTC ( [id://75663]=note: print w/replies, xml ) Need Help??


in reply to How do I find the index of a specific array value?

my @array = qw( your array here ); my $search_for = "here"; my( $index )= grep { $array[$_] eq $search_for } 0..$#array;

Replies are listed 'Best First'.
Re: Answer: how do i find the index of a specific array value?
by japhy (Canon) on Apr 26, 2001 at 04:04 UTC
      grep $array$_ eq $search_for, 0 .. $#array; will return matched array which stores the index of the matching words. my @index_arr = grep {$array$_ eq $search_for} 0 .. $#array; or my @index_arr = grep $array$_ eq $search_for, 0 .. $#array; foreach (@index_arr) { print "matching position = $_\n"; }
Re: Answer: how do i find the index of a specific array value?
by fenners (Beadle) on Aug 02, 2001 at 22:20 UTC
    Newbie question: I am very new to Perl and am a little confused about grep here.

    my ($index) = grep $array[$_] eq $search_for, 0 .. $#array;

    This is what I think is happening: grep is stepping through the range of numbers in list 0..$#array and substituting each in $_, and then using this as an index to find the corresponding element in @array. Eventually the expression $array[$_]eq $search_for is true and that element of the range 0..$#array is put into a list returned by grep, which is then assigned to ($index).

    This is my area of confusion: If @array has duplicate values, why does grep seem to stop when it finds the first value rather than produce a list of two values? Yet if I replace ($list) with @list, I get the index of both duplicate elements. I would greatly appreciate it if someone could cast some light on my darkness here :)

      I've got it! I think - this is a list, not an array, and according to Perlfaq4.pod (I know, I know, but I was looking under "grep") you can't push/pop a list as you can an array. This is also explained very well in the Perl Journal at http://www.tpj.com/articles/2001/0101/0101a/0101a.htm

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-03-28 13:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found