随着这个答案的继续,哇,我正在与我自己的 Moose“类型库”战斗 - 所以试图使用“ MooseX::Types ”。
基于上述MooseX::Types
文档,以及对上述答案的“hoobs”评论,我将自己的“类型”定义为下一个:
package MyTypes;
use 5.016;
use Moose;
use MooseX::Types -declare => [qw( Dir File )];
use MooseX::Types::Moose qw( Str );
use Path::Class::Dir;
use Path::Class::File;
class_type Dir, { class => 'Path::Class::Dir' };
coerce Dir, from Str, via { Path::Class::Dir->new($_) };
class_type File, { class => 'Path::Class::File' };
coerce File, from Str, via { Path::Class::File->new($_) };
1;
并在我的包裹中使用它
package MyDir;
use Moose;
use warnings;
use MyTypes qw(Dir); #to get the Dir type and its coercion
has 'path' => (
is => 'ro',
isa => Dir, # Dir is defined in the package MyTypes
required => 1,
);
1;
并尝试使用下一个短脚本
use 5.016;
use warnings;
use MyDir;
my $d = MyDir->new(path => "/tmp");
错误:
Attribute (path) does not pass the type constraint because: Validation failed for 'MyTypes::Dir' with value /tmp (not isa Path::Class::Dir) at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1279.
Moose::Meta::Attribute::verify_against_type_constraint(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", "instance", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1266
Moose::Meta::Attribute::_coerce_and_verify(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 536
Moose::Meta::Attribute::initialize_instance_slot(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), Moose::Meta::Instance=HASH(0x7f9e9b1c3588), MyDir=HASH(0x7f9e9b826bb8), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 525
Class::MOP::Class::_construct_instance(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 498
Class::MOP::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Class.pm line 284
Moose::Meta::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Object.pm line 28
Moose::Object::new("MyDir", "path", "/tmp") called at t.pl line 5
所以,不接受 'Str' 也不要强制。
以上几行有什么问题?我很确定这确实是一个非常小的错误,因为我遵循了 MooseX::Types 文档(至少我希望如此)-但找不到错误。
我开始对 Moose 真的绝望了,请帮助...
Ps:我的目标是在一个地方(包)定义我自己的所有“类型”,并在需要它们的任何地方使用它,只需一次“使用......”。