Book Home Programming PerlSearch this book

3.20. 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 (or use parentheses) no matter which variety of logical operators you use.

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 equivalent for $a xor $b is perhaps !$a != !$b. One could also write !$a ^ !$b or even $a ? !$b : !!$b, of course. The point is that both $a and $b have to evaluate to true or false in a Boolean context, and the existing bitwise operator doesn't provide a Boolean context without help.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.


HIVE: All information for read only. Please respect copyright!
Hosted by hive КГБ: Киевская городская библиотека