簡體   English   中英

Perl xor返回意外結果

[英]Perl xor returns unexpected result

這里發生了什么? 為什么不是$ 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

一直用

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是出於完全不同的原因而創建的。 喜歡orxor是一個邏輯運算符。 這意味着將整個操作數的真實性視為整體而不是逐位比較。 我不相信這是你想要的操作。

固定:

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

賦值的優先級高於xor。 寫吧:

$c = ($a xor $b);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM