Finding the First List Element That Passes a Test
Problem
You 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?”)[7] 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.
Solution
To find a matching value, use foreach to loop over
every element, and call last
as soon as you find a match:
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 for to loop a
variable over every array index, and call last as
soon as you find a match:
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
}Discussion
Not 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
foreach and for and call
last to ensure that we stop as soon as we find a
match. Before we use last to stop looking, though,
we save the value or index.
A common mistake is to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access