gpt4 book ai didi

perl - 驼鹿 (Perl) : convert undef to empty string or 0 rather than die()

转载 作者:行者123 更新时间:2023-12-04 05:42:31 25 4
gpt4 key购买 nike

我已收到 很多异常(exception)由于向我的 Moose 构造函数提供了不完整的数据,因此来自 QA。属性名称存在于构造函数参数中,但值为 undef .

对于许多脚本应用程序来说,事实就是如此undef .通常,这完全没问题。您不希望来自 warnings 的烦人警告pragma (所以你做 no warnings 'uninitialized' ),你当然不希望你的代码死,因为一个小值,比如门牌号码,是 undef .

所以不用多说,我希望我的 Moose 构造函数表现得像直接的 Perl(即没有 use warnings 'uninitialized'),也就是转换 undef0或根据需要使用空字符串。此示例中显示的尝试不适用于存在属性名称但值为 undef 的情况。 .我可以考虑使用 BUILDARGS实现我想要的。但是在没有 resorting to MooseX::UndefTolerant 的普通 Moose 中是否有一种声明方式? (不幸的是我不能使用它,因为它没有安装)?

package AAA;
use Moose;
has 'hu', is => 'ro', isa => 'Str';
has 'ba', is => 'ro', isa => 'Int';
no Moose; __PACKAGE__->meta->make_immutable;

package BBB;
use Moose; extends 'AAA';
has '+hu', default => ''; # don't want to die on undef
has '+ba', default => 0; # idem
no Moose; __PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;
# Those AAAs should die ...
throws_ok { AAA->new( hu => undef ) }
qr/Validation failed for 'Str' with value undef/;
throws_ok { AAA->new( ba => undef ) }
qr/Validation failed for 'Int' with value undef/;
# .. but these BBBs should live:
lives_ok { BBB->new( hu => undef ) } 'hu supplied as undef';
lives_ok { BBB->new( ba => undef ) } 'ba supplied as undef';
done_testing;

最佳答案

Moose::Manual::Types是一种有记录的方法来处理这种问题。

使用 Maybe[a]类型。

package AAA;
use Moose;

has 'hu', is => 'ro', isa => 'Str';
has 'ba', is => 'ro', isa => 'Int';

no Moose; __PACKAGE__->meta->make_immutable;


package BBB;
use Moose; extends 'AAA';

has 'hu', is => 'rw', isa => 'Maybe[Str]', default => ''; # will not die on undef
has 'ba', is => 'rw', isa => 'Maybe[Int]', default => 0; # idem

sub BUILD {
my $self = shift;
$self->hu('') unless defined $self->hu;
$self->ba(0) unless defined $self->ba;
}

no Moose; __PACKAGE__->meta->make_immutable;


package main;
use Test::More;
use Test::Exception;

# Those AAAs should die ...
throws_ok { AAA->new( hu => undef ) }
qr/Validation failed for 'Str' with value undef/;
throws_ok { AAA->new( ba => undef ) }
qr/Validation failed for 'Int' with value undef/;

# .. but these BBBs should live:
lives_ok { BBB->new( hu => undef ) } 'hu supplied as undef';
lives_ok { BBB->new( ba => undef ) } 'ba supplied as undef';

my $bbb = BBB->new( hu => undef, ba => undef );

is $bbb->hu, '', "hu is ''";
is $bbb->ba, 0, 'ba is 0';

done_testing;

关于perl - 驼鹿 (Perl) : convert undef to empty string or 0 rather than die(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6457825/

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