Lum*_*umi 8 perl moose undefined
由于不完整的数据被提供给我的Moose构造函数,我收到了很多 QA 例外.属性名称存在于构造函数参数中,但值为undef.
事实上,许多脚本应用程序都是生活中的事实undef.而且这通常很好.你不希望来自warningspragma 的烦人的警告(所以你这样做no warnings 'uninitialized'),你当然不希望你的代码死掉,因为一个小的值,比如房子号,就是undef.
所以不用多说,我希望我的Moose构造函数表现得像直接Perl(即没有use warnings 'uninitialized'),这是根据需要转换undef为0空字符串.此示例中显示的尝试不适用于存在属性名称但值为的情况undef.我可以想到BUILDARGS用来实现我想要的东西.但是,在没有使用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;
Run Code Online (Sandbox Code Playgroud)
在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;
Run Code Online (Sandbox Code Playgroud)