http://qs1969.pair.com?node_id=11134648


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.