Why does @array ~~ LIST return false, although @array contains the same elements as LIST?

I have

@a = (1,2,3); print (@a ~~ (1,2,3)) 

and

 @a = (1,2,3); print (@a == (1,2,3)) 

The first is the one that I expect to work, but does not print anything. The second prints 1.

Why? Doesn't the smart matching operator ~~ match in the case of @a ~~ (1,2,3) ?

+4
source share
3 answers

On the second, consider a slightly different

 \@a ~~ (1,2,3) 

~~ evaluates its arguments in a scalar context, so above is the same as

 scalar(\@a) ~~ scalar(1,2,3) 
  • \@a (in any context) returns a link to @a .
  • 1, 2, 3 in a scalar context is similar to do { 1; 2; 3 } do { 1; 2; 3 } do { 1; 2; 3 } , returning 3 .

So, minus a few warnings * above is equivalent

 \@a ~~ 3 

Actually you want

 \@a ~~ do { my @temp = (1,2,3); \@temp } 

which can be reduced to

 \@a ~~ [ 1,2,3 ] 

Finally, the magic ~~ allows \@a recorded as @a , so it can be shortened to

 @a ~~ [ 1,2,3 ] 

* - Always use use strict; use warnings; use strict; use warnings; !

+12
source

Smart match is trying to do what I think you would expect if you use an array or an array reference to the right, but not a list.

 $ perl -E '@a = (1, 2, 3); say (@a ~~ (1, 2, 3))' $ perl -E '@a = (1, 2, 3); say ((1, 2, 3) ~~ @a)' # also misguided, but different 1 $ perl -E '@a = (1, 2, 3); say (@a ~~ [1, 2, 3])' 1 
+9
source

Start with What is the difference between a list and an array? in perlfaq. It specifically shows how the wrong choice of values.

You can also start by writing down why you expected each of them to work or not to work so that we can correct your expectations. Why do you think you will get the expected results?

As for the smart match bits, there is no rule for ARRAY ~~ LIST . Predictive matching only works with pairs listed in the table in perlsyn. This will make him be one of these couples.

When you encounter these problems, try many more cases:

 #!perl use v5.10.1; use strict; use warnings; my @a = (1,2,3); say "\@a is @a"; say "\@a ~~ (1,2,3) is ", try( @a ~~ (1,2,3) ); say "\@a ~~ [1,2,3] is ", try( @a ~~ [1,2,3] ); say "\@a ~~ 3 is ", try( @a ~~ 3 ); say "3 ~~ \@a is ", try( 3 ~~ @a ); say ''; my @b = (4,5,6); say "\@b is @b"; say "\@b ~~ (4,5,6) is ", try( @b ~~ (4,5,6) ); say "\@b ~~ [4,5,6] is ", try( @b ~~ [4,5,6] ); say "\@b ~~ 3 is ", try( @b ~~ 3 ); say "3 ~~ \@b is ", try( 3 ~~ @b ); say ''; say "\@b ~~ \@a is ", try( @b ~~ @a ); sub try { $_[0] || 0 } 

The conclusion of various cases is the key that you do not read correctly in the documents:

 Useless use of a constant (2) in void context at test.pl line 8. Useless use of a constant (4) in void context at test.pl line 17. Useless use of a constant (5) in void context at test.pl line 17. @a is 1 2 3 @a ~~ (1,2,3) is 0 @a ~~ [1,2,3] is 1 @a ~~ 3 is 0 3 ~~ @a is 1 @b is 4 5 6 @b ~~ (4,5,6) is 0 @b ~~ [4,5,6] is 1 @b ~~ 3 is 0 3 ~~ @b is 0 @b ~~ @a is 0 
+6
source

Source: https://habr.com/ru/post/1398290/


All Articles