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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With