Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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

by stevieb (Canon)
on Jul 05, 2021 at 05:04 UTC ( #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";


|| 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?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2022-01-24 12:33 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (64 votes). Check out past polls.