当访问深 Hoh as Moose 属性中不存在的密钥时,我怎么会死呢?

发布于 2024-10-02 19:28:45 字数 969 浏览 8 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黄昏下泛黄的笔记 2024-10-09 19:28:45

一般来说,如果您有一个复杂的数据结构,想要以面向对象的方式处理,您应该将数据结构转换为对象树。通过 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.

尽揽少女心 2024-10-09 19:28:45

您可以考虑通过 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文