I was going over smart matches earlier this week and ran into an
inconsistancy that is confusing me. Let me show you a test case.
#!perl -w
use strict;
use feature qw(~~);
use Devel::Peek;
use Test::More qw(no_plan);
my $string = "5 hundred";
ok(5 ~~ "5", "The number 5 matches the string 5");
ok(5 ~~ $string, "Fails. RHS not brought into numeric context");
ok("5 hundred" ~~ 5, "Fails. It is commutative");
diag Dump $string;
{
no warnings "numeric";
ok(5 == $string, "Passes. RHS is brought into numeric context");
}
diag Dump $string;
ok(5 ~~ $string, "Fails. RHS is numeric, but ~~ doesn't care");
__END__
I'm having difficulty understanding why all the smart matches but the
first do not pass. Just to check, I tried all the above in a pugs from
June 20th, and the results are the same.
So, let me talk through the results and our current documentation, and
maybe someone can help. From the Perl 5 docs, a string on one side
and a number on the other should force numeric or string equality, but
doesn't exactly say which. For me, if it DWIM, it would return true
if either would return true.
Anyways, the first test works as expected. 5 ~~ "5" is OK.
The fourth test does a numeric equals between the number 5 and the
string "5 days". The string is forced into numeric context and
compares 5 to 5, returning true, as expected.
The second test is confusing. It would appear that it only does the
string comparison, gets false, and quits there. That seems to go
against the documentation saying that a number compared to something
like a number does a numeric comparison. Commutitivity is working as
the third test shows. Finally, in the fifth test, even with the
string upgraded to a PVNV, the smart match appears to continue
with a string comparison.
It seems to me that smart matching between scalars just isn't very smart.
Possibly, the docs need to be cleaned up to indicate the full and
correct hierarchy for matching with smart match. The other possibility
is that the smart match needs to be smarter, attempting numeric
comparisons if one side looks numeric, as the documentation currently
specifies. This would make the code do more of what I mean, so it
feels more natural. Does anyone else agree or am I missing a piece
of the puzzle with regards to Perl 6?
Steve Peters
steve@fisharerojo.org