http://www.perlmonks.org?node_id=824726

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

Dear Perl Monks,

I am trying to use the new MooseX::Declare syntax, in conjunction with Moose subtypes. Here is my code:
use strict; use v5.10; use MooseX::Declare; use Moose::Util::TypeConstraints; subtype 'PositiveInt' => as 'Int' => where { $_ > 0 } => message { "Number '$_' is not positive" }; class BankAccount { use MooseX::StrictConstructor; has balance => ( isa => 'Int', is => 'rw', default => 0 ); method deposit ( PositiveInt :$amount ) { $self->balance( $self->balance + $amount ); } } my $a = BankAccount->new( balance => 100 ); $a->deposit( amount => 50 ); say $a->balance;
This code gives the following error when executed:
'PositiveInt' could not be parsed to a type constraint - maybe you nee +d to pre-declare the type with class_type at /home/moose/perl5/lib/pe +rl5/MooseX/Declare/Syntax/MethodDeclaration.pm line 40
I haven't been able to find a class_type() method in the MooseX::Declare documentation. Could someone enlighten me about what should be done ?

Thank you in advance

Replies are listed 'Best First'.
Re: MooseX::Declare and Moose subtypes
by merlyn (Sage) on Feb 23, 2010 at 02:05 UTC
    Your problem is compile-time vs run-time. The subtype isn't being created until runtime, but it needs to be present at compiletime when you get to the method header. Solution: use BEGIN or put it in a separate file and "use" the file.

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      This works ! This is awesome !

      Thanks !!!