forced coercion
[email protected] (John Macdonald) Thu, 21 Aug 2014 21:23:00 +0000
| Newsgroups | perl.moose |
|---|---|
| Message-ID | <[email protected]> |
How do you code a subtype definition that forces a coercion to be used?
I have:
package My::Types;
use MooseX::Types -declare => [ qw( A chA nochA ) ];
sub _valid_A {
my $val = shift;
$val =~ /^(?:chr)A/
}
subtype A,
as Str,
where { _valid_A($_) };
subtype chrA;
coerce chrA, from A, via { s/^(?!chr)/chr/; $_ };
subtype nochA;
coerce nochrA, from A, via { s/^chr//; $_ };
Written that way, I get it dying:
MooseX::Types::TypeDecorator::AUTOLOAD(): Method 'create_child_type' is not supported for ...
If I change the target subtypes to have an "as Str" clause, it no longer dies but it accepts any string without appliying the coercion. The same happens if I use "as A".
So, how do I specify a type that starts with a base type, but then applies a coercion? All the examples I see of coercions have a "natural" base encoding, with the coercion providing a way to take some other type of value and turn it into the base - but when base is a validated string, it is hard to get it to actually use the coercion.
John Macdonald
Software Engineer
Ontario Institute for Cancer Research
MaRS Centre
661 University Avenue
Suite 510
Toronto, Ontario
Canada M5G 0A3
Tel:
Email: [email protected]
Toll-free: 1-866-678-6427
Twitter: @OICR_news
www.oicr.on.ca<http://www.oicr.on.ca/>
This message and any attachments may contain confidential and/or privileged information for the sole use of the intended recipient. Any review or distribution by anyone other than the person for whom it was originally intended is strictly prohibited. If you have received this message in error, please contact the sender and delete all copies. Opinions, conclusions or other information contained in this message may not be that of the organization.