【发布时间】:2014-03-17 21:59:25
【问题描述】:
现在有:
has 'id' => (
is => 'rw',
isa => 'Str',
default => sub { "id" . int(rand(1000))+1 }
);
工作正常,该:
PKG->new(id => 'some'); #the id is "some"
PKG->new() #the id is #id<random_number>
在下一个场景中:
my $value = undef;
PKG->new(id => $value);
(当然)出错了:
Attribute (id) does not pass the type constraint because: Validation failed for 'Str' with value undef at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-thread-multi-2level/Moose/Exception.pm line 37
问题是:
设置为undef后如何实现改变值(且仅当为$undef时)?所以,
has 'id' => (
is => 'rw',
isa => 'Str|Undef', #added undef to acceptable Type
default => sub { "id" . int(rand(1000))+1 }
);
现在,它接受$undef,但我不想要$undef,而是想要"id" . int(rand(1000))+1。 设置后如何更改属性值?
after 只为访问器调用,而不是为构造器调用。也许从Undef 到Str 的一些奇怪的coercion - 但仅 用于这一属性?
Ps:使用PKG->new( id => $value // int(rand(10000)) ) 不是一个可接受的解决方案。模块应该接受$undef,并且应该默默地将其更改为随机数。
【问题讨论】:
-
是否也想在使用 setter 后将 undef 更改为随机值?你在触发吗?
-
查看moose中的BUILD方法search.cpan.org/~ether/Moose-2.1204/lib/Moose/Manual/…
-
但是
$obj->id(undef)呢?