6.11. List Selections
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: 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 ); |