[Charlotte.PM] find index of array element

Dale Lancaster dale at lancaster.hm
Tue Mar 22 07:53:26 PST 2005


Good challenge and one I need to do every now and then.  Too bad grep 
doesn't return an index as an option.
The best I could come up with on short notice:

# Find first occurence of the number 3 in the list
my @input=(1,2,3,4,3,2,1) ;
my ($j, $i) ;
grep { $i++ ; $j=$i-1 if $_ =~ /3/  and !$j ; } @input ;
print $j ;

when run, produces "2", which would be correct.

dale

----- Original Message ----- 
From: "diona kidd" <diona at studio12a.com>
To: "Charlotte.PM" <charlotte at mail.pm.org>
Sent: Tuesday, March 22, 2005 10:02 AM
Subject: [Charlotte.PM] find index of array element


> Ok, I thought I'd start a discussion here before posting this to
> perlmonks. I have a little perl task that I often do and just as often
> forget how to do. I seem to recall doing it before with grep, map, or
> some combination. dunno....when I find out again, I'm going to post it
> on my site for reference.
>
> say you have an array and you want to find the index of a particular
> element by string comparison. You can do a foreach loop but I know
> there's a cleaner way...
>
> my @array = qw( item1 item2 item3 item4 );
>
> find the index of item3.
>
> anyone?
>
> _______________________________________________
> charlotte mailing list
> charlotte at pm.org
> http://mail.pm.org/mailman/listinfo/charlotte
> 



More information about the charlotte mailing list