Samn has asked for the wisdom of the Perl Monks concerning the following question:

Replies are listed 'Best First'.
Re: Checking for value in an array (without FOR)
by Fletch (Bishop) on Apr 19, 2002 at 19:09 UTC

    perldoc -f grep

Re: Checking for value in an array (without FOR)
by simon.proctor (Vicar) on Apr 19, 2002 at 19:11 UTC
    This is covered in perlfaq4 where a foreach loop is a method used for a single test. You could also use grep in scalar context but thats a bad idea. To see why look at the faq_monk node found here. Perlfaq4 also mentions why using grep may be a bad idea.

      That faq is somewhat out of date, as recent perls have been optimized such that map and grep don't build return lists if they're not required. As the benchmarking code below shows (numbers generated with 5.6.1 on a 1.2G Athlon):

      #!/usr/bin/perl use Benchmark qw( timethese cmpthese ); my @args = ( 100_000, { void => sub { grep { $_ == 50 } 0..100; 1 }, scalar => sub { my $res = grep { $_ == 50 } 0..100 }, list => sub { my @res = grep { $_ == 50 } 0..100 }, a_foreach => sub { my $match; foreach( 0..100 ) { $match++ if $_ == 50 } $match } } ); cmpthese( @args ); exit 0; __END__
      Benchmark: timing 100000 iterations of a_foreach, list, scalar, void...
       a_foreach:  4 wallclock secs ( 4.52 usr +  0.01 sys =  4.53 CPU) @ 22075.06/s (n=100000)
            list:  4 wallclock secs ( 3.35 usr +  0.00 sys =  3.35 CPU) @ 29850.75/s (n=100000)
          scalar:  3 wallclock secs ( 3.34 usr +  0.00 sys =  3.34 CPU) @ 29940.12/s (n=100000)
            void:  4 wallclock secs ( 3.29 usr +  0.00 sys =  3.29 CPU) @ 30395.14/s (n=100000)
                   Rate a_foreach      list    scalar      void
      a_foreach 22075/s        --      -26%      -26%      -27%
      list      29851/s       35%        --       -0%       -2%
      scalar    29940/s       36%        0%        --       -1%
      void      30395/s       38%        2%        2%        --
      

      There's practically no difference between grep in scalar and list context, while a foreach loop runs 26% slower.

      Update: Oops, I'd said foreach was 35% slower. Changed the last paragraph above.

      Update: Playing around, if you use grep EXPR, LIST rather than grep BLOCK LIST (i.e. grep $_ == 50, 0..100), that gap grows to 33% (since there's not as much overhead entering and leaving the block). If you switch comparisons from $_ == 50 to /50/ and stick with the BLOCK form, the foreach form is 45% faster.

        a_foreach could be faster, as it is in perlfaq4.