FAQ 4.45 How do I find the first array element for which a condition is true?

Discussion in 'Perl Misc' started by PerlFAQ Server, Mar 11, 2011.

  1. This is an excerpt from the latest version perlfaq4.pod, which
    comes with the standard Perl distribution. These postings aim to
    reduce the number of repeated questions as well as allow the community
    to review and update the answers. The latest version of the complete
    perlfaq is at http://faq.perl.org .

    --------------------------------------------------------------------

    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.
     
    PerlFAQ Server, Mar 11, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. -
    Replies:
    12
    Views:
    696
    Remon van Vliet
    Jun 15, 2005
  2. Replies:
    3
    Views:
    305
    Paul Rubin
    Feb 25, 2007
  3. bdb112
    Replies:
    45
    Views:
    1,347
    jazbees
    Apr 29, 2009
  4. Bill W.
    Replies:
    13
    Views:
    295
    Phillip Gawlowski
    May 9, 2011
  5. \A_Michigan_User\
    Replies:
    4
    Views:
    154
    Thomas 'PointedEars' Lahn
    Nov 16, 2007
Loading...

Share This Page