Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is simple XOR not working in Perl?

Tags:

perl

xor

my $list = "1 3";
my @arr  = split " ", $list;
my $c    = $arr[0] ^ $arr[1];
print $c, "\n";

The above is giving an abnormal character.

It should give answer as 2, since 1 XOR 3 is 2.

like image 323
Saurabh Shrivastava Avatar asked Dec 19 '22 11:12

Saurabh Shrivastava


1 Answers

^ considers the internal storage format of its operand to determine what action to perform.

>perl -E"say( 1^3 )"
2

>perl -E"say( '1'^'3' )"
☻

The latter xors each character of the strings.

>perl -E"say( chr( ord('1')^ord('3') ) )"
☻

You can force numification by adding zero.

>perl -E"@a = split(' ', '1 3'); say( (0+$a[0])^(0+$a[1]) )"
2

>perl -E"@a = map 0+$_, split(' ', '1 3'); say( $a[0]^$a[1] )"
2

Technically, you only need to make one of the operands numeric.

>perl -E"@a = split(' ', '1 3'); say( (0+$a[0])^$a[1] )"
2

>perl -E"@a = split(' ', '1 3'); say( $a[0]^(0+$a[1]) )"
2
like image 199
ikegami Avatar answered Dec 31 '22 13:12

ikegami