Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

MooseX::Declare and Moose subtypes

by Anonymous Monk
on Feb 22, 2010 at 22:57 UTC ( #824726=perlquestion: print w/replies, xml ) Need Help??
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/ 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 !!!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://824726]
Approved by biohisham
[choroba]: Yes, (...)+ only returns the last match

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2018-01-19 08:48 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (216 votes). Check out past polls.