ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
4.12. Finding the First List Element That Passes a TestProblemYou want the first element in the list (or its index) that passes a test. Alternatively, you want to know whether any element passes the test. The test can be simple identity ("Is this element in the list?")[1] or more complex ("I have a list of Employee objects, sorted from highest salary to lowest. Which manager has the highest salary?"). Simple cases normally only require the value of the element, but when the array itself will be altered, you probably need to know the index number of the first matching element.
SolutionTo find a matching value, use my($match, $found, $item); foreach $item (@array) { if ($criterion) { $match = $item; # must save $found = 1; last; } } if ($found) { ## do something with $match } else { ## unfound } To find a matching index, use my($i, $match_idx); for ($i = 0; $i < @array; $i++) { if ($criterion) { $match_idx = $i; # save the index last; } } if (defined $match_idx) { ## found in $array[$match_idx] } else { ## unfound } DiscussionNot having a built-in mechanism to do this, we must write our own code to go through the list and test each element. We use A common mistake is to try to use We have to set Here's an example. Assume that foreach $employee (@employees) { if ( $employee->category() eq 'engineer' ) { $highest_engineer = $employee; last; } } print "Highest paid engineer is: ", $highest_engineer->name(), "\n"; When we're searching and only want the index, we can save some code by remembering that for ($i = 0; $i < @ARRAY; $i++) { last if $criterion; } if ($i < @ARRAY) { ## found and $i is the index } else { ## not found } See AlsoThe "For Loops," "Foreach Loops," and "Loop Control" sections of perlsyn (1) and Chapter 2 of Programming Perl; the |