--------------------------------------------------------------------
4.45: How do I find the first array element for which a condition is true?
To find the first array element which satisfies a condition, you can use
the "first()" function in the "List::Util" module, which comes with Perl
5.8. This example finds the first element that contains "Perl".
use List::Util qw(first);
my $element = first { /Perl/ } @array;
If you cannot use "List::Util", you can make your own loop to do the
same thing. Once you find the element, you stop the loop with last.
my $found;
foreach ( @array ) {
if( /Perl/ ) { $found = $_; last }
}
If you want the array index, you can iterate through the indices and
check the array element at each index until you find one that satisfies
the condition.
my( $found, $index ) = ( undef, -1 );
for( $i = 0; $i < @array; $i++ ) {
if( $array[$i] =~ /Perl/ ) {
$found = $array[$i];
$index = $i;
last;
}
}
--------------------------------------------------------------------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.