[Melbourne-pm] Smart-matching objects

Toby Corkindale toby.corkindale at strategicdata.com.au
Mon Feb 15 17:10:26 PST 2010


A little gotcha about smart matching of objects in 5.10.0 vs 5.10.1:

In both, you can attempt to match two blessed objects, eg:
if ($person ~~ @people) ..

In 5.10.0, this will do a useless comparison that definitely won't do 
what you want.
In 5.10.1, this will fail altogether, unless you define an overloaded 
smartmatch operation in the objects.

But if you DO define an overloaded smart match, then the behaviour varies.

This is the syntax for overloading the smart match operator:
use overload '~~' => sub { my ($left, $right) = @_; ... }


In 5.10.0, you will receive the verbatim items from the left and right 
of the ~~ in your code, ie:
$left = $person
$right = $people[0] (followed by the rest of @people if you keep shifting)

Or if you did ($person ~~ \@people) you would get:
$left = $person
$right = \@people


However in 5.10.1, they (sensibly, I think) expand stuff out a bit, so 
you will have your matching subroutine called multiple times, ie:
$left = $person, $right = $people[0]
$left = $person, $right = $people[1]
$left = $person, $right = $people[2]



I'd prefer to just code for the 5.10.1 syntax and not look back, but I 
think it's only in private projects that I have the luxury of being able 
to set "use 5.10.1;" at the top of my scripts ;)

tjc.


More information about the Melbourne-pm mailing list