Why doesn't simple XOR work in Perl?

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

      

The above gives an abnormal character.

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

+3


source to share


2 answers


^

examines the format of its operand's internal memory to determine what action to take.

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

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

      

The last character of each character in strings.

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

      



You can force the numbering 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

      

+8


source


There are two problems here:

  • $c1

    and $c2

    start with undefined.
  • These are lines.

(I assume there is a little missing, so that 'c1' and 'c2' are retrieved as the first / last element of the list, 1 and 3 respectively)



Try:

$list="1 2 3";
@arr=split(" ",$list);
$c=int($arr[0])^int($arr[2]);
print "$c";

      

the function int

explicitly sets a numeric value.

+2


source







All Articles