以下脚本智能匹配两个数组的切片.一开始,两个阵列都是一样的,我得到了合理的结果.然后我改变其中一个数组并智能匹配两个新切片,但它仍然说切片是相同的.但是,当我将切片复制到数组中时,对数组进行智能匹配表明它们确实不同.
剧本:
#!/usr/bin/perl use warnings; use strict; use diagnostics; my @x = qw (one two); my @y = qw (one two); my @x_s; my @y_s; print "Before change: values are the same:\n"; @x_s = @x[0,1]; @y_s = @y[0,1]; print "\@x_s: @x_s\n"; print +(@x[0,1] ~~ @y[0,1]) ? "equal\n" : "not equal\n"; print +(@x_s ~~ @y_s) ? "equal\n" : "not equal\n"; $x[0]='three'; print "After change: values should be different:\n"; @x_s = @x[0,1]) ? "equal\n" : "not equal\n"; print +(@x_s ~~ @y_s) ? "equal\n" : "not equal\n";
输出:
Before change: values are the same: @x_s: one two equal equal After change: values should be different: @x_s: three two equal not equal
我正在使用Perl 5.10.1,这对于数组切片和散列切片都会发生.为什么会这样?
解决方法
看起来智能匹配在带有切片的标量上下文中工作.
请考虑以下代码段:
你的情况:
#!/usr/bin/perl my @foo = (1,2); my @bar = (3,4); print @foo[1,2] ~~ @bar[1,2] ? "Equal\n" : "Not equal\n";
这可能就是你所需要的:
#!/usr/bin/perl my @foo = (1,4); print [ @foo[1,2] ] ~~ [ @bar[1,2] ] ? "Equal\n" : "Not equal\n";