Perl xor返回意外结果

时间:2017-08-03 15:09:32

标签: perl xor

这里发生了什么?为什么不是$ 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

2 个答案:

答案 0 :(得分:11)

始终使用

use strict;
use warnings qw( all );

它会检测到您的优先问题。

Useless use of logical xor in void context

具体地,

$c = $a xor $b;

装置

($c = $a) xor $b;

运营商andornotxor的优先级非常低。这使andornot对流量控制非常有用。

... 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);
相关问题