tags:

views:

432

answers:

2

Hi, 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

+6  A: 

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

use Moose::Util::TypeConstraints;
oylenshpeegul
+4  A: 

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 );
singingfish
Email::Valid++ # regexes for mail validation is evil
brunov
converter42