Why does smartmatch return true when comparing slices of an array that should be different?

The following script are intelligent combinations of slices of two arrays. At the beginning, both arrays are the same, and I get reasonable results. Then I change one of the arrays and smart match two new fragments, but it still says the fragments are identical. However, when I copy slices into arrays, smart array matching shows that they are really different.

script:

#!/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]; @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"; 

Exit:

 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 

I use Perl 5.10.1, and this happens for both slicing an array and hash fragments. Why is this happening?

+8
perl smartmatch
source share
3 answers

Smart matching seems to work in a scalar context with slices.

Consider the following code snippets:

Your case:

 #!/usr/bin/perl my @foo = (1,2); my @bar = (3,4); print @foo[1,2] ~~ @bar[1,2] ? "Equal\n" : "Not equal\n"; 

Perhaps you need:

 #!/usr/bin/perl my @foo = (1,2); my @bar = (3,4); print [ @foo[1,2] ] ~~ [ @bar[1,2] ] ? "Equal\n" : "Not equal\n"; 
+5
source share

The smart match ~~ statement does its magic for arrays, not lists. The array network is a list, not an array.

Update:

You can solve this by simply including your fragments in brackets, since intellectual matches are automatically played out:

 print +([@x[0,1]] ~~ [@y[0,1]]) ? "equal\n" : "not equal\n"; 
+3
source share

Originally posted by askucins

I ran a quick query in Perl docs related to the different behavior of this test and the version of Perl, and I found that this was fixed in Perl 5.13.5. See "Smart array matching" in perl5135delta :

Previously, the following code led to a successful match:

 my @a = qw(a y0 z); my @b = qw(a x0 z); @a[0 .. $#b] ~~ @b; 

This strange behavior has now been fixed [ perl # 77468 ].

0
source share

All Articles