问题
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