这里发生了什么?为什么不是$ c == 1?
$ cat y.pl
#!/usr/bin/perl
$a = 0;
$b = 1;
$c = $a xor $b;
print "$a ^ $b = $c\n";
$ ./y.pl
0 ^ 1 = 0
答案 0 :(得分:11)
始终使用
use strict;
use warnings qw( all );
它会检测到您的优先问题。
Useless use of logical xor in void context
具体地,
$c = $a xor $b;
装置
($c = $a) xor $b;
运营商and
,or
,not
和xor
的优先级非常低。这使and
,or
和not
对流量控制非常有用。
... or die ...;
... or next;
xor
不会发生短路,因此对流量控制无效。 xor
的创建原因完全不同。与or
一样,xor
是逻辑运算符。这意味着将整个操作数的真实性视为整体而不是逐位比较。我不相信这是你想要的操作。
修正:
$c = $a ^ $b;
Low
Precedence
Operation Bitwise Logical Logical
---------- ---------- ---------- ----------
NOT ~ ! not
AND & && and
OR | || or
OR* N/A // N/A
XOR ^ N/A xor
OR* - Like OR, but only undefined is considered false.
答案 1 :(得分:2)
赋值的优先级高于xor。只需写下:
$c = ($a xor $b);