当访问深 Hoh as Moose 属性中不存在的密钥时,我怎么会死呢?
我有一个 Moose 对象,其属性是哈希:
has 'custom_fields' => (
traits => [qw( Hash )],
isa => 'HashRef',
builder => '_build_custom_fields',
handles => {
custom_field => 'accessor',
has_custom_field => 'exists',
custom_fields => 'keys',
has_custom_fields => 'count',
delete_custom_field => 'delete',
},
);
around 'custom_field' => sub {
my $orig = shift // confess;
my $self = shift // confess;
my $field = shift // confess;
confess "Attempt accessing non-existing custom field '$field'"
unless ( @_ or $self->has_custom_field($field) );
$self->$orig( $field, @_ );
};
他非常适合简单的一级哈希。现在我想允许深度哈希(哈希的哈希的哈希......),并且每当尝试访问不存在的(可能是深度的)密钥时仍然承认
。
更新 也许以某种方式使用Data::Diver
?
I have a Moose object with an attribute that is hash:
has 'custom_fields' => (
traits => [qw( Hash )],
isa => 'HashRef',
builder => '_build_custom_fields',
handles => {
custom_field => 'accessor',
has_custom_field => 'exists',
custom_fields => 'keys',
has_custom_fields => 'count',
delete_custom_field => 'delete',
},
);
around 'custom_field' => sub {
my $orig = shift // confess;
my $self = shift // confess;
my $field = shift // confess;
confess "Attempt accessing non-existing custom field '$field'"
unless ( @_ or $self->has_custom_field($field) );
$self->$orig( $field, @_ );
};
his works well for simple, one level hashes. Now I would like to allow deep hashes (hash of hashes of hashes ...) and still confess
whenever an access to a non-existing (possibly deep) key is attempted.
UPDATE
Perhaps somehow use Data::Diver
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,如果您有一个复杂的数据结构,想要以面向对象的方式处理,您应该将数据结构转换为对象树。通过 Moose 强制,这也可以相当透明地建模。
Generally I'd say, if you have a complex data structure that you want to handle in an object oriented manner, you should turn the data structure into a tree of objects. With Moose coercions this can be modeled rather transparently as well.
您可以考虑通过
autovivification
关闭自动复活。您可以传递
unimport
例程'exception'
使其死亡,它可能已自动生存。You could look at turning off autovivification through
autovivification
.You can pass the
unimport
routine'exception'
which makes it die, where it might have autoviv-ed.