驼鹿:子类型消息不显示
Moose: subtype message does not show up
我开始使用 Moose。这是我的测试包代码:
package MyTest;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'MyStatus',
as 'Int',
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
has status => ( is => 'rw', isa => 'Maybe[MyStatus]' );
no Moose; 1;
程序如下:
use strict;
use warnings;
use MyTest;
my $t1 = MyTest->new('status' => 3);
$t1->status(100);
我原以为会得到一个 "Wrong status: 100" 错误,但我却得到了这个:
属性(状态)未通过类型约束,因为:'Maybe[MyStatus]' 的验证失败,访问器 MyTest::s 的值为 100 tatus(在 MyTest.pm 行定义10) 第 4 行
如何使该消息生效?
谢谢!
Maybe[]
吃错信息。如果删除它,它会根据您的类型提供 message
。
has status => ( is => 'rw', isa => "MyStatus" );
这是错误:
Attribute (status) does not pass the type constraint because: Wrong status: 100 at accessor MyTest::status (defined at /home/foo/code/scratch.pl line 1331) line 4
MyTest::status('MyTest=HASH(0x3434c58)', 100) called at /home/foo/code/scratch.pl line 1337
因为Maybe[]
本身也只是一个函数调用。它使用您传递给构造函数的值(此处为 100
)检查调用 MyStatus
后面的代码引用的 return 值。如果该类型检查通过,则一切正常。但如果检查失败,Maybe[]
会发出自己的错误消息。
你应该问自己这个问题:你真的希望 status
可以是 undef
吗?你没有做到required
,所以你可以省略它。那么您的对象没有状态,这与 undefined 状态不同。状态意味着对象处于某种状态,其中该状态具有意义。如果该状态未定义,这对我来说听起来很麻烦。
我开始使用 Moose。这是我的测试包代码:
package MyTest;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'MyStatus',
as 'Int',
where { $_ >= 0 && $_ < 10 },
message { "Wrong status: $_" };
has status => ( is => 'rw', isa => 'Maybe[MyStatus]' );
no Moose; 1;
程序如下:
use strict;
use warnings;
use MyTest;
my $t1 = MyTest->new('status' => 3);
$t1->status(100);
我原以为会得到一个 "Wrong status: 100" 错误,但我却得到了这个:
属性(状态)未通过类型约束,因为:'Maybe[MyStatus]' 的验证失败,访问器 MyTest::s 的值为 100 tatus(在 MyTest.pm 行定义10) 第 4 行
如何使该消息生效? 谢谢!
Maybe[]
吃错信息。如果删除它,它会根据您的类型提供 message
。
has status => ( is => 'rw', isa => "MyStatus" );
这是错误:
Attribute (status) does not pass the type constraint because: Wrong status: 100 at accessor MyTest::status (defined at /home/foo/code/scratch.pl line 1331) line 4 MyTest::status('MyTest=HASH(0x3434c58)', 100) called at /home/foo/code/scratch.pl line 1337
因为Maybe[]
本身也只是一个函数调用。它使用您传递给构造函数的值(此处为 100
)检查调用 MyStatus
后面的代码引用的 return 值。如果该类型检查通过,则一切正常。但如果检查失败,Maybe[]
会发出自己的错误消息。
你应该问自己这个问题:你真的希望 status
可以是 undef
吗?你没有做到required
,所以你可以省略它。那么您的对象没有状态,这与 undefined 状态不同。状态意味着对象处于某种状态,其中该状态具有意义。如果该状态未定义,这对我来说听起来很麻烦。