2009-03-21 32 views
10

私はちょうど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 => '[email protected]' 
); 
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. 

はムースでカスタム電子メールサブタイプを作成する方法を誰もが知っている、私はそれが次のコードのようになりますと信じドキュメントから

ムースバージョン:0.72 perlバージョン:5.10.0、 プラットフォーム:LinuxをUbuntuの8.10

答えて

14

私もMOOSEに新しいですが、私はsubtypeのために、あなたは

を追加する必要があると思います
use Moose::Util::TypeConstraints; 
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); 
+1

メール::メールの検証の有効++#の正規表現は悪 – brunov

+4

@brunoですが、 v - &Email :: Valid :: rfc822は検証のために正規表現を使います。 – converter42

関連する問題