开发者

Why does smartmatch return different values depending on the order of the operands?

开发者 https://www.devze.com 2023-02-16 03:43 出处:网络
I have an array for which the follo开发者_如何转开发wing test returns true: 1 ~~ @a And yet, the following test returns false:

I have an array for which the follo开发者_如何转开发wing test returns true:

1 ~~ @a

And yet, the following test returns false:

@a ~~ 1

I read in Learning Perl that the placement of the values on either side of the smartmatch operator doesn't matter, but obviously in the above code it does. Why is that? Are the two statements checking different things?


In addition to the other answers, the list of Perl 5.10.1 changes has a section on changes made to the ~~ operator:

The smart match operator ~~ is no longer commutative. The behaviour of a smart match now depends primarily on the type of its right hand argument.

So Learning Perl may have been correct prior to these changes.


The version of ~~ in 5.10.0 was based on the then current perl6 design, which was commutative. Because 5.10.0 took so very long to be released, by the time it came out, the perl6 smartmatch had been greatly improved (including no longer being commutative), but no one in perl5 development noticed in time to fix perl5's implementation. It was fixed in 5.10.1, and no one should rely on the older 5.10.0 rules. It's news to me that the inconsistent behavior got documented in a printed book.


You can see that it does very different things depending on the order and types of its arguments if you go to Smart Matching in Detail.


If Learning Perl says that, it's wrong outdated (although it does tend to work out that way in many cases). What the smart matching operator does is mainly determined by the type of the right argument; see the table in the perlsyn documentation for specifics.

0

精彩评论

暂无评论...
验证码 换一张
取 消