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