gpt4 book ai didi

perl - Moose如何仅在$undef时更改属性值?

转载 作者:行者123 更新时间:2023-12-04 23:22:00 25 4
gpt4 key购买 nike

现在有:

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只为访问器调用而不为构造函数调用。也许有些奇怪 coercion来自 UndefStr - 但仅针对这一属性?

ps:使用 PKG->new( id => $value // int(rand(10000)) )不是一个可接受的解决方案。模块应该接受 $undef并且应该默默地将其更改为随机数。

最佳答案

Type::Tiny其目标之一是让向单个属性添加强制转换变得非常容易。这是一个例子:

use strict;
use warnings;

{
package Local::Test;
use Moose;
use Types::Standard qw( Str Undef );

my $_id_default = sub { "id" . int(rand(1000)+1) };

has id => (
is => 'rw',
isa => Str->plus_coercions(Undef, $_id_default),
default => $_id_default,
coerce => 1,
);

__PACKAGE__->meta->make_immutable;
}

print Local::Test->new(id => 'xyz123')->dump;
print Local::Test->new(id => undef)->dump;
print Local::Test->new->dump;

你也可以看看 MooseX::UndefTolerant这使得 undef传递给构造函数的值就像它们被完全省略一样。不过,这不包括将 undef 传递给访问器;只是构造函数。

关于perl - Moose如何仅在$undef时更改属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22466361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com