你如何在穆斯创建子类型?

时间:2009-03-21 00:20:00

标签: perl types moose

我刚刚开始使用Moose

我正在创建一个简单的通知对象,并希望检查输入是否为“电子邮件”类型。 (暂时忽略简单的正则表达式匹配)。

从文档中我认为它应该类似于以下代码:

# --- 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";

但我收到以下错误:

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.

任何人都知道如何在Moose中创建自定义电子邮件子类型?

穆斯版:0.72 perl-version:5.10.0, 平台:linux-ubuntu 8.10

2 个答案:

答案 0 :(得分:14)

我也是Moose的新手,但我想subtype,你需要添加

use Moose::Util::TypeConstraints;

答案 1 :(得分:10)

这是我之前从食谱中偷走的那个:

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 );