kdjantzen has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

in a Moose::Role I defined two subtypes

subtype 'OptInt' => as 'Int'; subtype 'OptStr' => as 'Str';
With
use Types::Standard qw(Maybe Str Int OptInt OptStr);
I want to specify an attribute of a class
has 'xxx' => (is => 'rw', isa => (Maybe[OptInt])->plus_coercions(OptInt, sub{ + undef }));
which, understandably, results in the error message
Could not find sub 'OptInt' to export in package 'Types::Standard' at
How should I specify my subtypes in order to make the above work?

Thanks for any help.

K.D.J.

Replies are listed 'Best First'.
Re: Moose subtypes
by 1nickt (Canon) on Oct 06, 2016 at 19:23 UTC

    Hi K.D.J.

    Here's how I do it in Moo. The Type::Tiny libs work seamlessly with Moose, I believe, so this code should Moosify as is.

    package My::Types; use strict; use warnings; use parent 'Type::Library'; use Type::Utils; # gets you sugar, 'declare' etc. use Types::Standard qw/ Maybe Str Int /; declare 'OptInt', as Maybe[Int], message {'must be integer or nothing' +}; declare 'OptStr', as Maybe[Str], message {'must be string or nothing'} +; 1;
    package My::Class; use Moo; use My::Types qw/ :all /; has optional_numeric_arg => ( is => 'ro', isa => OptInt ); has optional_string_arg => ( is => 'ro', isa => OptStr ); 1;

    Note that as an added benefit this also gets you an importable is_TypeName function for each type you declare that can be used anywhere for simple data validation.

    ( I believe I first learned of these techniques in This Advent Calendar article. )

    Hope this helps...

    The way forward always starts with a minimal test.
      Hello 1nickt,

      thanks for the very helpful information.
      Using it I got my code working as I wanted it.