10.1. A Bit Illogical

Perl has several ways of saying and and or:

Table 10-1. And, Or, and Xor Operators in Perl
Operation AND OR XOR
bitwise (non-short-circuiting) & | ^
logical (high precedence) && ||  
logical (low precedence) and or xor

(There is no high-precedence logical XOR operator.) The consequences of picking an operator from the wrong row are usually annoying mistakes like

open (FH, $file) | die "Error opening $file: $!
";

which dies whether or not the open succeeds, because the | operator is strictly a bitwise arithmetic or string operator, which evaluates both of its operands so that it can return the result of ORing their bits together. In this case, you want ||, which is a logical operator that evaluates its left-hand side and returns it if true; otherwise it evaluates and returns its right-hand side.

An even better choice would be the or operator introduced in Perl 5, which has such low precedence that you can leave out the parentheses on open:

open FH, $file or die "Error opening $file: $!
";

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset