CoffeeMonster
CoffeeMonster

Reputation: 2190

How do you create subtypes in Moose?

I'm just starting to use Moose.

I'm creating a simple notification object and would like to check inputs are of an 'Email' type. (Ignore for now the simple regex match).

From the documentation I believe it should look like the following code:

# --- contents of message.pl --- #
package Message;
use Moose;

subtype 'Email' => as 'Str' => where { /.*@.*/ } ;

has 'subject' => ( isa => 'Str', is => 'rw',);
has 'to'      => ( isa => 'Email', is => 'rw',);

no Moose; 1;
#############################
package main;

my $msg = Message->new( 
    subject => 'Hello, World!', 
    to => '[email protected]' 
);  
print $msg->{to} . "\n";

but I get the following errors:

String found where operator expected at message.pl line 5, near "subtype 'Email'"
    (Do you need to predeclare subtype?)
String found where operator expected at message.pl line 5, near "as 'Str'"
    (Do you need to predeclare as?)
syntax error at message.pl line 5, near "subtype 'Email'"
BEGIN not safe after errors--compilation aborted at message.pl line 10.

Anyone know how to create a custom Email subtype in Moose?

Moose-version : 0.72 perl-version : 5.10.0, platform : linux-ubuntu 8.10

Upvotes: 10

Views: 2264

Answers (2)

singingfish
singingfish

Reputation: 3167

Here's one I stole from the cookbook earlier:

package MyPackage;
use Moose;
use Email::Valid;
use Moose::Util::TypeConstraints;

subtype 'Email'
   => as 'Str'
   => where { Email::Valid->address($_) }
   => message { "$_ is not a valid email address" };

has 'email'        => (is =>'ro' , isa => 'Email', required => 1 );

Upvotes: 10

oylenshpeegul
oylenshpeegul

Reputation: 3424

I am new to Moose as well, but I think for subtype, you need to add

use Moose::Util::TypeConstraints;

Upvotes: 13

Related Questions