Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Multiple condition IF statement using grep and eq

by Anonymous Monk
on May 04, 2016 at 16:53 UTC ( [id://1162203]=perlquestion: print w/replies, xml ) Need Help??

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

I have a IF statement in this form:

if (grep $_ == $F[1],73,89,121,101,117,69,77,67,115,81,97,65,113) {

That compares values held within $F1 to those listed. I wish to add an additional condition that checks another variable other than $F1 but i'm struggling somewhat with the syntax and how this will work with the grep. For example:

if (grep $_ == $F[1],73,89,121,101,117,69,77,67,115,81,97,65,113 && $inext eq "Global.SAM")

Each condition works individually, but the latter condition testing $inext is ignored when written in this form. Why is this happening and what could be a solution to the problem?

Replies are listed 'Best First'.
Re: Multiple condition IF statement using grep and eq
by toolic (Bishop) on May 04, 2016 at 17:05 UTC
    Use parentheses to group your terms.

    Tip #6 from the Basic debugging checklist: B::Deparse

    perl -MO=Deparse,p if (grep(($_ == $F[1]), 73, 89, 121, 101, 117, 69, 77, 67, 115, 81, 97 +, 65, $inext eq 'Global.SAM')) {

    Change your code to:

    if ( (grep $_ == $F[1],73,89,121,101,117,69,77,67,115,81,97,65,113) && + ($inext eq "Global.SAM") ) {
      Thank you! I knew it would be something simple. That tip is going to be super useful too.
        As further suggestion, move the "cheap test" to the front. Grep implies a foreach loop and is much more "expensive" than a simple equality test. The "if" statement is executed from left to right - don't bother with the grep if the first test fails.

        Also consider the block form of grep:

        if ($inext eq "Global.SAM" and grep{$_ == $F[1]} 73,89,121,101,117,69,77,67,115,81,97,65,113) {}
        "and" is a lower priority operator than "&&" so no extra parens required.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1162203]
Approved by herveus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (7)
As of 2024-04-23 14:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found