in reply to Re: my 'if' condition doesn't work, why?
in thread my 'if' condition doesn't work, why?

The core List::Util first function is like grep but returns the first element found:
use List::Util qw(first); for my $n (0 .. 267) { print "$n\n" if first {$n == $_} 40, 47, 76; }
and so should be faster for very large lists.

Replies are listed 'Best First'.
Re^3: my 'if' condition doesn't work, why?
by AnomalousMonk (Archbishop) on Nov 12, 2014 at 12:10 UTC

    A problem with List::Util::first() as used in the example above is that it actually returns the first element from the list that satisfies the condition. If this value happens to be false, the if-statement modifier will not satisfied, and the dependent statement will not be executed. Neither any nor grep nor a hash lookup have this problem.

    c:\@Work\Perl>perl -wMstrict -le "use List::Util qw(first); ;; for my $n (0 .. 267) { printf qq{$n } if first {$n == $_} 40, 0, 47, 76; } print qq{\n----------}; ;; ;; for my $n (0 .. 267) { printf qq{$n } if grep { $n == $_ } 40, 0, 47, 76; } " 40 47 76 ---------- 0 40 47 76

Re^3: my 'if' condition doesn't work, why?
by GrandFather (Saint) on Nov 12, 2014 at 08:03 UTC

    On average 50% faster which often doesn't help much. However if speed is an issue and the search needs to be done multiple times with the same data, using a hash lookup is a much better solution.

    Perl is the programming world's equivalent of English