Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

index and rindex for arrays

by MeowChow (Vicar)
on Apr 26, 2001 at 08:20 UTC ( [id://75710]=CUFP: print w/replies, xml ) Need Help??

Just like the title says :-) Avoid greping through your entire array.

Takes optional non-negative positions like index and rindex. Does a stringwise compare, so be mindful of cases like '0' ne '0.0'

sub aindex (\@$;$) { my ($aref, $val, $pos) = @_; for ($pos ||= 0; $pos < @$aref; $pos++) { return $pos if $aref->[$pos] eq $val; } return -1; } sub raindex (\@$;$) { my ($aref, $val, $pos) = @_; for (defined $pos or $pos = $#$aref; $pos >= 0; $pos--) { return $pos if $aref->[$pos] eq $val; } return -1; } ## EXAMPLE ## my @l = qw(are you looking for something here or are you not); print " ", aindex @l, 'you'; print " ", aindex @l, 'you', 5; print " ", raindex @l, 'you'; print " ", raindex @l, 'you', 5; # output: 1 8 8 1

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-25 06:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found