in reply to Weird grep behaviour

According to the Perl manpage:
"In particular, it is not limited to using regular expressions"
Changing it to use a regex ( /$var1/ ) worked, but I still don't understand why it didn't previously.

Chris

Replies are listed 'Best First'.
Re^2: Weird grep behaviour
by snoopy (Curate) on Oct 17, 2007 at 07:57 UTC
    You grep expression is in the form:grep EXPR,LIST. But EXPR is fixed as $var1 - not a regexp or code block.

    grep will return the whole list or an empty list depending on whether $var evaluates to true or false. Consider:

    my @arr1 = ('a'); foreach my $var1 (0, 1) { if( grep($var1, @arr1) ) { print "match $var1\n"; } else { print "fail $var1\n"; } }
  • nothing is returned when $var1 is 0 (false)
  • the entire list is returned when $var1 is 1 (true)
  • Update: Here's a sample usage:

    #!/usr/bin/perl use warnings;use strict; my $paid = 0; # :-( my @shopping = ( 'twinkies','coffee', (grep !$paid => 'gruel', 'cabbage', 'cordial'), (grep $paid => 'caviar', 'truffles', 'champagne'), ); print "@shopping";
Re^2: Weird grep behaviour
by naikonta (Curate) on Oct 17, 2007 at 07:44 UTC
    Well, I think because your filter was so loose everything gets through. With /$var1/, the filter is pretty strict.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!