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

故事扮演 提交于 2019-12-08 16:22:54

问题


I have an array for which the following 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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5279917/why-does-smartmatch-return-different-values-depending-on-the-order-of-the-operan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!