2009-03-21 16 views
10

Właśnie zaczynam używać Moose.Jak tworzyć podtypy w Moose?

Tworzę prosty obiekt powiadomienia i chciałbym sprawdzić, czy dane wejściowe są typu "E-mail". (Zignoruj ​​na razie proste dopasowanie do wyrażenia regularnego).

Z dokumentacji wierzę powinien wyglądać w następujący kod:

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

ale otrzymuję następujące błędy:

 
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. 

ktoś wie jak utworzyć niestandardową podtyp Email w Moose?

Moose wersja: 0.72 Perl wersja: 5.10.0, platforma: linux-ubuntu 8.10

Odpowiedz

14

Jestem nowy w Moose, jak również, ale myślę, że dla subtype, trzeba dodać

use Moose::Util::TypeConstraints; 
10

Oto jeden Wygrałem z poradnikiem wcześniej:

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

Email :: Prawidłowe ++ # Wyrażenia regularne dla sprawdzania poczty elektronicznej jest zła – brunov

+4

@bruno v - & Email :: Valid :: rfc822 używa wyrażenia regularnego do sprawdzania poprawności. – converter42