我试图弄清楚将Moose纳入我的项目的正确方法。 Here我发现了一篇文章,建议应该在类型库中组织Moose类型,这似乎是一个好主意。所以我根据提供的示例编写了以下代码:
文件1:MyTypeLib.pm
package MyTypeLib;
use MooseX::Types -declare => [ qw( MyStatus ) ];
use MooseX::Types::Moose qw/Int/;
subtype MyStatus,
as Int,
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
1;
文件2:MyTest.pm
package MyTest;
use MyTypeLib qw( MyStatus );
use Moose;
has status => ( is => 'rw', isa => 'MyStatus' );
no Moose; 1;
文件3:MyMain.pl
use strict;
use warnings;
use MyTest;
my $t1 = MyTest->new('status' => 5);
当我运行它时,我收到此消息:
属性(status)不传递类型约束,因为: “MyStatus”的验证失败,值为5(不是isa MyStatus)at C:\ Strawberry \ perl \ vendor \ lib \ Moose \ Object.pm第24行
当我在MyTest.pm中保留子类型定义并且不使用MooseX :: Types时,一切都按预期工作。但重点是将子类型移动到单独的包中,并在其他包中使用它们。 有人可以建议如何使其工作,或指向(或发布)一些工作示例,或建议实现目标的替代方法。
谢谢!
答案 0 :(得分:2)
Remove the quotes: isa => MyStatus
, not isa => 'MyStatus'
. MyStatus
is a constant-like function exported from your type library. Providing a string rather than a proper type constraint for isa
("stringy types") causes it to be looked up in Moose's type registry, or, if it's not found there, it's interpreted as the name of a class, and the type is inferred to be "any object of that class or its subclasses". Stringy types are less explicit and less flexible than using actual types, and more prone to conflicts since they all share a global namespace. It's best not to use them and type lbraries at the same time.
答案 1 :(得分:0)
这似乎有效
MyTypeLib.pm
package MyTypeLib;
use Moose::Util::TypeConstraints;
subtype MyStatus =>
as 'Num' =>
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
#coerce MyStatus => from Int => via { $_ };
1;
MyTest.pm
package MyTest;
use MyTypeLib;
use Moose;
has status => ( is => 'rw',
isa => 'MyStatus',
#coerce => 1 i
);
no Moose; 1;
MyMain.pl
use strict;
use warnings;
use MyTest;
use Data::Dumper;
my $t1 = MyTest->new( status => 5);
print Dumper $t1;
my $t2 = MyTest->new( status => 10);
哪个给出了
$ perl MyMain.pl
$VAR1 = bless( {
'status' => 5
}, 'MyTest' );
Attribute (status) does not pass the type constraint because: Wrong
status: 10 at /System/Library/Perl/Extras/5.18/darwin-thread-multi-
2level/Moose/Exception.pm line 37
Moose的这方面信息不多,但看起来Moose::Util::TypeConstraints
是将MooseX模块折叠成驼鹿。
EDIT 删除了强制!
你还需要明确的强制.-