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

This task is almost what grep is designed for:

for my $n (0 .. 267) { print "$n\n" if grep {$n == $_} 40, 47, 76; }

with the slight down side that the compare is evaluated for each item in the list always. Most of the time that won't be an issue, but if it is (for a large list of possibilities) then you could instead:

my %wanted = map {$_ => 1} 40, 47, 76; for my $n (0 .. 267) { print "$n\n" if exists $wanted{$n}; }
Perl is the programming world's equivalent of English

Replies are listed 'Best First'.
Re^2: my 'if' condition doesn't work, why?
by eyepopslikeamosquito (Archbishop) on Nov 12, 2014 at 07:45 UTC
    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.

      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

      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