Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

logical AND "&&"

by odegbon (Initiate)
on Jan 30, 2010 at 23:27 UTC ( [id://820519]=perlquestion: print w/replies, xml ) Need Help??

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

I was just wondering if I could make comparison by joining a bunch of if statements with 3 "ANDs" like so:

if(($a == 1 && $b < 2) && ($d < 4 && $e >= 6)){ do something ...

Replies are listed 'Best First'.
Re: logical AND "&&"
by toolic (Bishop) on Jan 31, 2010 at 02:00 UTC
    Yes, you can. If you can't remember Operator Precedence and Associativity, then just add more parentheses so that there is no doubt.
    if ( (($a == 1) && ($b < 2)) && (($d < 4) && ($e >= 6)) ){ do somethin +g ...
    The and operator can also be used in place of &&. and has lower precedence, but the following is the same as the above:
    if ( (($a == 1) and ($b < 2)) and (($d < 4) and ($e >= 6)) ){ do somet +hing ...
      Thanks, Toolic
Re: logical AND "&&"
by Corion (Patriarch) on Jan 30, 2010 at 23:29 UTC

    What happened when you tried?

Re: logical AND "&&"
by YuckFoo (Abbot) on Jan 30, 2010 at 23:32 UTC
    No, you may not.
    #!/usr/bin/perl use strict; my ($a, $b, $d, $e) = (1, 1, 1, 7); if(($a == 1 && $b < 2) && ($d < 4 && $e >= 6)) { print "Trying is fun!\n" };
      Hi YuckFoo, did you say I may not? But I ran your code and it worked
        My bad, go ahead and do it.

        There is much iffing and anding to be done!

        Code coder, code!

        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: logical AND "&&"
by ikegami (Patriarch) on Jan 31, 2010 at 17:05 UTC
    In fact,
    if (($a == 1 && $b < 2) && ($d < 4 && $e >= 6)) {
    could be written as
    if ($a == 1 && $b < 2 && $d < 4 && $e >= 6) {
      I heard you could write
      if($a==1&&$b<2&&$d<4&&$e>=6){

        It wasn't clear if he knew the parens weren't necessary. Also, it wasn't clear if he knew that

        if (($a == 1 && $b < 2) && ($d < 4 && $e >= 6)) {
        is the same as
        if ($a == 1 && ($b < 2 && ($d < 4 && ($e >= 6))) {

        Those are the two things I pointed out in my post. I wasn't trying to say that parens are bad. In this case, though, spacing can also provide clear disambiguation

        if ($a==1 && $b<2 && $d<4 && $e>=6) {

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2024-04-19 19:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found