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

Re: Perldoc's explanation of the difference between '&&' and 'and' has me confused

by stevieb (Canon)
on Jul 05, 2021 at 05:04 UTC ( [id://11134648]=note: print w/replies, xml ) Need Help??


in reply to Perldoc's explanation of the difference between '&&' and 'and' has me confused

They are identical in functionality. Where they differ is precedence. || and && have a higher precedence than and and or. Observe:

use warnings; use strict; my $one = 1; $one += 0 || warn "||\n"; $one += 0 or warn "or\n"; $one += 0 && warn "&&\n"; $one += 0 and warn "and\n";

Output:

|| and

All examples attempt the same thing. Add $one to zero, which should obviously result in true (1). However, in the || example, instead of $one being added to zero, the || has a higher precedence than +=, meaning that the || binds to the zero before the addition-assignment happens, so the left hand side is false, therefore, the warn is executed. In the or line, the += has a higher precedence, meaning the left hand side is evaluated to true, so the warn is ignored.

It's similar for the && and and. && binds to the zero before the +=, so the left side is always going to be false, so the right side (warn) is never evaluated. With and, the addition happens first, then the and evaluation and because the LHS is true, the warn is executed.

Clear as mud? Good. Whenever you're using and or && || and you get results you don't expect, it's almost always related to precedence, especially in long convoluted evaluations where you're using negations and stuff.

Parens allow you to create your own precedence:

($one += 0) || warn "||\n";

There, whatever is in parens will be evaluated first before the || is brought into the mix. In this case, the || warning isn't thrown like it was above.

Log In?
Username:
Password:

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

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

    No recent polls found