10

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 => 'coolkids@example.com' 
);  
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

Axeman
  • 29,660
  • 2
  • 47
  • 102
CoffeeMonster
  • 2,160
  • 4
  • 20
  • 34

2 Answers2

13

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

use Moose::Util::TypeConstraints;
cjm
  • 61,471
  • 9
  • 126
  • 175
oylenshpeegul
  • 3,404
  • 1
  • 18
  • 18
10

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 );
simbabque
  • 53,749
  • 8
  • 73
  • 136
singingfish
  • 3,136
  • 22
  • 25