> Is there a Perl function that returns the index of a given element in an 
array?  For example: 

my @list = q( apple  banana  pear  grapefruit); 
my $look4 = "banana"; 
my $ndx = somefunc( $look4, @list ); # sets $ndx to 1 
$look4 = "monkeywrench"; 
$ndx = somefunc( $look4, @list); # sets $ndx to -1, or maybe undef? 

Usually, looking for the index is a sign of a data structure issue. Arrays 
are, by nature, not data addressable, that's what hashes are for.  A trick 
would be to transform it into a hash (w/ the index as the value) and look 
that way but that's only elegant in the eye of certain transformer folks. 
You can *just* determine if it's in there by grep:
my $in_there = grep { /^banana$/ } @list;

Or you could, if you hadn't tricked us:
my @list = q( apple  banana  pear  grapefruit); 

returns a single string i.e
$list[0] eq ' apple banana pear grapfruit';

You want "quote word" ;->
my @list = qw( apple  banana  pear  grapefruit); 

anyway. You can turn it into a hash:
my $in_there = grep { /^$look4$/ } @list;
my $cnt = 0;
my %at_where = map {  $_ => $cnt++; } @list;
print "Yep $at_where{$look4}\n" if $in_there;

You can try a map in a void context:
my $at_where = 0;
my $cnt = 0;
map {  $cnt++; $at_where = $cnt -1 if /^$look4$/  ; } @list;

but, as LW says "I wouldn't want to map anybody in a void context" ... or 
words to that effect.

a

Andy Bach
Systems Mangler
Internet: [EMAIL PROTECTED]
VOICE: (608) 261-5738  FAX 264-5932

Wire telegraph is a kind of a very, very long cat. You pull his tail in
New York and his head is meowing in Los Angeles. And radio operates
exactly the same way. The only difference is that there is no cat.
 --Albert Einstein (explaining radio)
_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to