Приглашаем посетить
Прутков (prutkov.lit-info.ru)

Section 6.11.  List Selections

Previous
Table of Contents
Next

6.11. List Selections

Use grep and first instead of for when searching for values in a list.

The same principles apply when you want to refine a list by removing unwanted elements. Instead of a for loop:

    
    # Identify candidates who are unfit for the cut-and-thrust of politics...
    my @disqualified_candidates;
    for my $name (@candidates) {
        if (cannot_tell_a_lie($name)) {
            push @disqualified_candidates, $name;
        }
    }

just use a grep:


    

    # Identify candidates who are unfit for the cut-and-thrust of politics...
my @disqualified_candidates = grep {cannot_tell_a_lie($_)} @candidates;

Likewise, don't use a for when you're searching a list for a particular element:

    
    # Victimize someone at random...
    my $scapegoat = $disqualified_candidates[rand @disqualified_candidates];

    # Unless there's a juicier story...
    SEARCH:
    for my $name (@disqualified_candidates) {
        if (chopped_down_cherry_tree($name)) {
            $scapegoat = $name;
            last SEARCH;
        }
    }

    # Publish and be-damn...
    print {$headline} "Disgraced $scapegoat Disqualified From Election!!!\n";

Using the first function often results in code that is both more comprehensible and more efficient:


    use List::Util qw( first );

    
# Find a juicy story...
my $scapegoat = first { chopped_down_cherry_tree($_) } @disqualified_candidates;
# Otherwise victimize someone at random...
if (!defined $scapegoat) { $scapegoat = $disqualified_candidates[rand @disqualified_candidates]; }
# Publish and be-damn...
print {$headline} "Disgraced $scapegoat Disqualified From Election!!!\n";

    Previous
    Table of Contents
    Next