[英]Why is simple XOR not working in Perl?
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.它应该给出答案 2,因为 1 XOR 3 是 2。
^
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. 后者xrs字符串的每个字符。
>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
Two problems here: 这里有两个问题:
$c1
and $c2
are undefined at the start. $c1
和$c2
在开始时未定义。 (I'll assume there's a bit missing, such that 'c1' and 'c2' get extracted as first/last element of the list, 1 and 3 respectively) (我假设有一点缺失,这样'c1'和'c2'被提取为列表的第一个/最后一个元素,分别为1和3)
Try: 尝试:
$list="1 2 3";
@arr=split(" ",$list);
$c=int($arr[0])^int($arr[2]);
print "$c";
the int
function explicitly casts to a numeric value. int
函数显式转换为数值。
Perl v5.26 has a feature to force numeric context on the bitwise operators : Perl v5.26 具有在按位运算符上强制使用数字上下文的功能:
use v5.26;
use feature qw(bitwise);
my $list = "1 3";
my @arr = split " ", $list;
my $c = $arr[0] ^ $arr[1];
print $c, "\n";
Over time, perl has changed/improved it's handling of bitwise string operations.随着时间的推移,perl 已经改变/改进了它对按位字符串操作的处理。
The answer is not simple, and there are numeric, and bitwise xor operations in perl. I'll refer you to the Bitwise-String-Operators section of the manual.答案并不简单,perl中有数字和按位异或运算。我会推荐你参考手册的按位字符串运算符部分。 Note how they are now trying to address this "unpredictable behavior" by using the "bitwise" feature, new/experimental in Perl 5.22, stable in Perl 5.28 ( see brian d foy's article Make bitwise operators always use numeric context that he mentions in the comments below ).
请注意他们现在如何尝试通过使用“按位”功能来解决这种“不可预测的行为”,Perl 5.22 中的新功能/实验性功能,Perl 5.28 中的稳定功能(请参阅 brian d foy 的文章Make bitwise operators always use numeric context ,他在下面的评论)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.