2009-03-21 37 views
10

Tôi chỉ mới bắt đầu sử dụng Moose.Làm cách nào để tạo các kiểu con trong Moose?

Tôi đang tạo một đối tượng thông báo đơn giản và muốn kiểm tra đầu vào là loại 'Email'. (Bỏ qua cho bây giờ các trận đấu regex đơn giản).

Từ các tài liệu tôi tin rằng nó sẽ giống như đoạn mã sau:

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

nhưng tôi nhận được các lỗi sau đây:

 
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. 

Bất cứ ai cũng biết làm thế nào để tạo ra một subtype Email tùy chỉnh ở Moose?

Moose phiên bản: 0,72 perl-phiên bản: 5.10.0, nền tảng: Linux-Ubuntu 8.10

Trả lời

14

Tôi mới vào Moose là tốt, nhưng tôi nghĩ rằng cho subtype, bạn cần phải thêm

use Moose::Util::TypeConstraints; 
10

Dưới đây là một tôi đã đánh cắp từ sách dạy nấu ăn trước đó:

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 :: trị ++ # regexes để xác nhận mail là ác – brunov

+4

@bruno v - & Email :: Hợp lệ :: rfc822 sử dụng regex để xác thực. – converter42

Các vấn đề liên quan