简体   繁体   English

Perl xor返回意外结果

[英]Perl xor returns unexpected result

What's going on here? 这里发生了什么? Why isn't $c == 1 ? 为什么不是$ 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

Always use 一直用

use strict;
use warnings qw( all );

It would have detected your precedence issue. 它会检测到您的优先问题。

Useless use of logical xor in void context

Specifically, 特别,

$c = $a xor $b;

means 手段

($c = $a) xor $b;

The operators and , or , not and xor have very low precedence. 运算符andornotxor优先级非常低。 This makes and , or and not very useful for flow control. 这使得andornot流控制是非常有用的。

... or die ...;
... or next;

xor doesn't short-circuit, so it's not useful for flow control. xor不会短路,因此对流量控制没有用。 xor was created for an entirely different reason. xor是出于完全不同的原因而创建的。 Like or , xor is a logical operator. 喜欢orxor是一个逻辑运算符。 That means considers the truth of its operand as whole instead of doing bit-by-bit comparisons. 这意味着将整个操作数的真实性视为整体而不是逐位比较。 I don't believe this is the operation you want. 我不相信这是你想要的操作。

Fix: 固定:

$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.

Precedence of the assignment is higher than xor. 赋值的优先级高于xor。 Just write: 写吧:

$c = ($a xor $b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM