The apprentice nervously requests feedback from the more experienced...
Given a small set of sorted values stored in an array, is this an idiomatic way to find the index of a given value?
sub getArrayIndex # -------------------------------------------------------------- # When given a scalar and an array, this either returns the # of the scalar in the array or -1 (not found). # -------------------------------------------------------------- { my $value = shift; my @values = @_; my $result = -1; for ( my $index = 0; $index < @values; $index++ ) { if ( $value eq $values[ $index ] ) { $result = $index; last; } } return $result; }
Assorted Notes:
The arrays I'm working with are relatively small (~50 elements each) and I'm only looking for a direct, case-sensitive match.
This node (and perlfaq4) suggests that a hash may be more appropriate. However, the array contains values in a required (non-trivial) order, so a hash doesn't seem feasible. Am I mistaken?
This node provides a solution, however perlfaq4 suggests grep is inefficent. Is that true?
My approach is based on one found in the CookBook (p112), but I wonder if there's an easier way or if I'm confused--again.
It seems to work in my limited testing, however, I'm worried that I might be following a meme, CCP, or just plain not grokking something.
--f
In reply to Idiomatic Array Index Search? by footpad
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |