我正在尝试使用自定义 init_arg 将序列化添加到具有所需属性的 Moose 类(在属性名称前加上破折号以保持 API 一致性),似乎这会导致解包失败。我在下面设置了一个测试用例来说明我的观点。
use strict;
use warnings;
package MyClass1;
use Moose;
use MooseX::Storage;
use namespace::autoclean;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
required => 1,
);
__PACKAGE__->meta->make_immutable;
package MyClass2;
use Moose;
use MooseX::Storage;
use namespace::autoclean;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
required => 1,
init_arg => '-my_attr',
);
__PACKAGE__->meta->make_immutable;
package main;
my $inst1 = MyClass1->new(my_attr => 'The String');
my $packed1 = $inst1->pack;
my $unpacked1 = MyClass1->unpack($packed1); # this works
my $inst2 = MyClass2->new(-my_attr => 'The String');
my $packed2 = $inst2->pack;
my $unpacked2 = MyClass2->unpack($packed2); # this fails with a ...
# ... Attribute (my_attr) is required at ...
更新:进一步调查表明问题是打包时没有考虑 init_arg 。因此,即使使用自定义 init_arg 的非必需属性在解包后也无法正确恢复。请参阅此附加测试用例:
package MyClass3;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
init_arg => '-my_attr',
);
# in main...
my $inst3 = MyClass3->new(-my_attr => 'The String');
my $packed3 = $inst3->pack;
my $unpacked3 = MyClass3->unpack($packed3); # this seems to work ...
say $unpacked3->my_attr; # ... but my_attr stays undef
非常感谢您的帮助,丹尼斯