问题描述
我通常使用 Storable
和 nstore
,但现在我有一个 模块 具有 CODE
并且显然 Storable
不喜欢那样.
I was usually using Storable
with nstore
, but now I have a module that has CODE
and apparently Storable
doesn't like that.
我发现了 YAML
(和 YAML::XS
,我真的不能开始工作).我还对 MooseX::Storage 进行了一些试验,但没有取得多大成功.
I found YAML
(and YAML::XS
which I can't really get to work).I also experimented a bit with MooseX::Storage without much success.
还有其他选择吗?你会推荐什么?
Are there other alternatives?What would you recommend?
推荐答案
您可以使用 Data::Dumper 将 $Data::Dumper::Deparse
设置为真值后,但这仅用于调试目的,而不用于序列化.
You can dump a coderef with Data::Dumper after setting $Data::Dumper::Deparse
to a true value, but this is only intended for debugging purposes, not for serialization.
我建议你回去看看为什么 MooseX::Storage 不适合你,因为作者真的很努力地为 Moose 对象序列化提供了一个抽象的、健壮的解决方案.
I would suggest you go back to looking at why MooseX::Storage isn't working out for you, as the authors tried really hard to present a well-abstracted and robust solution for Moose object serialization.
更新:看起来您在序列化 _offset_sub
属性时遇到了问题,如 这个问题.由于该属性有一个构建器,并且它的构造相当简单(它只查看另一个属性的当前值),因此您根本不需要序列化它——当您反序列化您的对象并想再次使用它时,构建器将在您第一次调用 $this->offset
时被调用.因此,您应该能够将其标记为不序列化":
Update: it looks like you are running into issues serializing the _offset_sub
attribute, as described in this question. Since that attribute has a builder, and its construction is fairly trivial (it just looks at the current value of another attribute), you shouldn't need to serialize it at all -- when you deserialize your object and want to use it again, the builder will be invoked the first time you call $this->offset
. Consequently, you should just be able to mark it as "do not serialize":
use MooseX::Storage;
has '_offset_sub' => (
is => 'ro',
isa => 'CodeRef',
traits => [ 'DoNotSerialize' ],
lazy => 1,
builder => '_build_offset_sub',
init_arg => undef,
);
最后,这有点正交,但你可以折叠 offset
和_offset_sub
使用原生属性 'Code' trait 将属性组合在一起:
Lastly, this is somewhat orthogonal, but you can fold the offset
and_offset_sub
attributes together by using the native attribute 'Code' trait:
has offset => (
is => 'bare',
isa => 'CodeRef',
traits => [ qw(Code DoNotSerialize) ],
lazy => 1,
builder => '_build_offset',
init_arg => undef,
handles => {
offset => 'execute_method',
},
);
sub _build_offset {
my ($self) = @_;
# same as previous _build_offset_sub...
}
这篇关于哪些推荐的 Perl 模块可以序列化 Moose 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!