On 9 Jul 2008, at 09:09, David Kaufman wrote:
 # from the POD doco at
 #
http://search.cpan.org/~gbarr/Scalar-List-Utils-1.19/lib/List/Util.pm#DESCRIPTION

 $foo = first { defined($_) } @list;  # first defined value in @list


Who needs to install a CPAN module to do that? I personally would have
written it as:

 $foo = (grep defined, @list)[0];  # first defined value in @list


Bear in mind that first may be much more efficient if the list is large and/or the test is expensive:

$ cat foo.pl
use List::Util qw( first );

sub even {
    my ( $where, $x ) = @_;
    print "$where is checking $x\n";
    return $x % 2 == 0;
}

my @in = ( 1, 2, 3, 4, 5 );

my $first_even = first { even( 'first', $_ ) } @in;
my $grep_even = ( grep { even( 'grep', $_ ) } @in )[0];

print "$first_even, $grep_even\n";

$ perl foo.pl
first is checking 1
first is checking 2
grep is checking 1
grep is checking 2
grep is checking 3
grep is checking 4
grep is checking 5
2, 2

I'm not suggesting that necessarily applies in this case - just a general observation.

--
Andy Armstrong, Hexten



Reply via email to