What's going on here? Why isn't $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. This makes and
, or
and not
very useful for flow control.
... or die ...;
... or next;
xor
doesn't short-circuit, so it's not useful for flow control. xor
was created for an entirely different reason. Like or
, xor
is a logical operator. 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. Just write:
$c = ($a xor $b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.