Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 513
Ikram Hawramani Avatar asked Mar 12 '11 00:03

Ikram Hawramani


4 Answers

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.

like image 179
Quick Joe Smith Avatar answered Jun 02 '23 08:06

Quick Joe Smith


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.

like image 20
ysth Avatar answered Jun 02 '23 06:06

ysth


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.

like image 45
Jonathan Leffler Avatar answered Jun 02 '23 07:06

Jonathan Leffler


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.

like image 22
Anomie Avatar answered Jun 02 '23 06:06

Anomie