Subject: | Use of hashref to declare coercions is problematic |
Given the following type definition:
subtype "SmallInt", as "Int", where { $_ < 10 };
coerce "SmallInt",
from Num => via { 1 },
from Str => via { 2 };
The value "33.333" will be coerced to "1".
But if you define the type this way:
subtype "SmallInt", as "Int", where { $_ < 10 };
coerce "SmallInt",
from Str => via { 2 },
from Num => via { 1 };
Then "33.333" will be coerced to "2".
It matters what order you define the coercions in. The earlier one
"wins".
If you define a per-attribute coercion like this:
has small => (
traits => [ "CoercePerAttribute" ],
is => "ro",
isa => "SmallInt",
coerce => {
Num => sub { 1 },
Str => sub { 2 },
},
);
there's no way of knowing whether the Num coercion will win, or Str
will, because hashes are unordered in Perl.