Perl xor returns unexpected result

What's going on here? Why not $ 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

      

+3


source to share


2 answers


Always use

use strict;
use warnings qw( all );

      

It will detect your problem with priority.

Useless use of logical xor in void context

      

In particular,

$c = $a xor $b;

      

means

($c = $a) xor $b;

      



Operators and

, or

, not

and xor

have a very low priority. It does and

, or

and is not

very useful for flow control.

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

      

xor

is not short-circuited, so it is not suitable for flow control. xor

was created for a completely different reason. As or

, xor

is a logical operator. This means that the truth of its operand is integer, not a bitwise comparison. 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.

      

+11


source


Destination priority is higher than xor. Just write:



$c = ($a xor $b);

      

+2


source







All Articles