perlfaq4: How do I find the first array element for which a condition is true?

[email protected] (_brian_d_foy)
Newsgroups perl.perlfaq.workers,perl.documentation
Message-ID <040920021815105090%[email protected]>
* How do I find the first array element for which a condition is true?
   + added List::Util::first example
   + added foreach example for those without List::Util
   + adjusted for() example to match the other two.

i'm also trying something new - the first sentence of the answer includes 
the question and the answer.

Index: perlfaq4.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq4.pod,v
retrieving revision 1.31
diff -u -d -r1.31 perlfaq4.pod
--- perlfaq4.pod        4 Sep 2002 22:32:19 -0000       1.31
+++ perlfaq4.pod        4 Sep 2002 23:06:42 -0000
@@ -1265,16 +1265,37 @@
 
 =head2 How do I find the first array element for which a condition is true?
 
-You can use this if you care about the index:
+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".
 
-    for ($i= 0; $i < @array; $i++) {
-        if ($array[$i] eq "Waldo") {
-           $found_index = $i;
-            last;
-        }
-    }
+       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.
 
-Now C<$found_index> has what you want.
+       my $found;
+       foreach my $element ( @array )
+               {
+               if( /Perl/ ) { $found = $element; 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, $i ) = ( undef, -1 );
+    for( $i = 0; $i < @array; $i++ ) 
+       {
+        if( $array[$i] =~ /Perl/ ) 
+               { 
+               $found = $array[$i];
+               $index = $i; 
+               last;
+               }
+        }
 
 =head2 How do I handle linked lists?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.