Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Weird grep behaviour

by snoopy (Deacon)
on Oct 17, 2007 at 07:57 UTC ( #645394=note: print w/ replies, xml ) Need Help??


in reply to Re: Weird grep behaviour
in thread Weird grep behaviour

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";


    Comment on Re^2: Weird grep behaviour
    Select or Download Code

    Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Node Status?
    node history
    Node Type: note [id://645394]
    help
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (9)
    As of 2014-07-11 10:19 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      When choosing user names for websites, I prefer to use:








      Results (224 votes), past polls