| Newsgroups |
perl.cvs.perlfaq |
| Message-ID |
<[email protected]> |
cvsuser 02/09/10 12:49:38
Modified: . perlfaq4.pod
Log:
* 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.
Revision Changes Path
1.32 +31 -10 perlfaq/perlfaq4.pod
Index: perlfaq4.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq4.pod,v
retrieving revision 1.31
retrieving revision 1.32
diff -u -w -r1.31 -r1.32
--- perlfaq4.pod 4 Sep 2002 22:32:19 -0000 1.31
+++ perlfaq4.pod 10 Sep 2002 19:49:38 -0000 1.32
@@ -1,6 +1,6 @@
=head1 NAME
-perlfaq4 - Data Manipulation ($Revision: 1.31 $, $Date: 2002/09/04 22:32:19 $)
+perlfaq4 - Data Manipulation ($Revision: 1.32 $, $Date: 2002/09/10 19:49:38 $)
=head1 DESCRIPTION
@@ -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:
-
- for ($i= 0; $i < @array; $i++) {
- if ($array[$i] eq "Waldo") {
- $found_index = $i;
+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 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;
}
}
-
-Now C<$found_index> has what you want.
=head2 How do I handle linked lists?