Logical and, or, not, and xor
As lower precedence alternatives to &&, ||, and !,
Perl provides the and, or, and not
operators. The behavior of these operators is identical—in particular,
and and or short circuit like their counterparts, which
makes them useful not only for logical expressions but also for control
flow.
Since the precedence of these operators is much lower than the ones borrowed from C, you can safely use them after a list operator without the need for parentheses:
unlink "alpha", "beta", "gamma"
or gripe(), next LINE;With the C-style operators you’d have to write it like this:
unlink("alpha", "beta", "gamma")
|| (gripe(), next LINE);But you can’t just up and replace all instances of || with or.
Suppose you change this:
$xyz = $x || $y || $z;
to this:
$xyz = $x or $y or $z; # WRONG
That wouldn’t do the same thing at all! The precedence of the
assignment is higher than or but lower
than ||, so it would always assign
$x to $xyz and then do the ors. To get the same effect as ||, you’d have to write:
$xyz = ( $x or $y or $z );
The moral of the story is that you still must learn precedence no matter which variety of logical operators you use. We suggest you use parentheses for any such construct that might confuse the reader, even if you’re not confused.[68]
There is also a logical xor
operator that has no exact counterpart in C or Perl, since the only other
exclusive or operator (^) works on bits. The xor operator can’t short circuit since both sides must be evaluated. The best ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access