Unblessing Perl 对象并为 Convert_blessed 构造 TO_JSON 方法

2024-03-28

In 这个答案 https://stackoverflow.com/a/4185679/632407我找到了一个简单的推荐TO_JSON方法,将受祝福的对象序列化为 JSON 时需要该方法。

sub TO_JSON { return { %{ shift() } }; }

有人可以详细解释一下它是如何工作的吗?

我把它改为:

sub TO_JSON {
        my $self = shift;         # the object itself – blessed ref
        print STDERR Dumper $self;

        my %h = %{ $self };       # Somehow unblesses $self. WHY???
        print STDERR Dumper \%h;  # same as $self, only unblessed

        return { %h };    # Returns a hashref that contains a hash.
        #return \%h;      # Why not this? Works too…
}

很多问题…:(简单来说,我无法理解 3 行 Perl 代码。;(

我需要TO_JSON但它会过滤掉:

  • 不需要的属性和
  • 也取消设置属性(例如,对于那些has_${attr}谓词返回 false)

这是我的代码 - 它有效,但我真的不明白为什么不祝福有效......

use 5.010;
use warnings;
use Data::Dumper;

package Some;
use Moo;

has $_ => ( is => 'rw', predicate => 1,) for (qw(a1 a2 nn xx));

sub TO_JSON {
    my $self = shift;
    my $href;
    $href->{$_} = $self->$_ for( grep {!/xx/} keys %$self );
    # Same mysterious unblessing. The `keys` automagically filters out
    # “unset” attributes without the need of call of the has_${attr}
    # predicate… WHY?
    return $href;
}

package main;
use JSON;
use Data::Dumper;

my @objs = map { Some->new(a1 => "a1-$_", a2 => "a2-$_", xx=>"xx-$_") } (1..2);
my $data = {arr => \@objs};
#say Dumper $data;
say JSON->new->allow_blessed->convert_blessed->utf8->pretty->encode($data);

EDIT: 澄清一下问题:

  • The %{ $hRef }取消引用$hRef(获取引用指向的哈希值),但是为什么要从 a 获取普通哈希值受祝福的对象引用 $self?
  • 换句话说,为什么$self是哈希引用吗?
  • 我尝试制作一个哈希片,例如@{$self}{ grep {!/xx/} keys %$self}但没有成功。因此我创造了那个可怕的TO_JSON.罢工>
  • If the $self是一个 hashref,为什么keys %$self仅返回具有值的属性,而不返回所有声明的属性(例如nn也——参见has)?

sub TO_JSON { return { %{ shift() } }; }
                     | |  |
                     | |  L_ 1. pull first parameter from `@_`
                     | |        (hashref/blessed or not)
                     | |     
                     | L____ 2. dereference hash (returns key/value list)
                     |
                     L______ 3. return hashref assembled out of list

In your TO_JSON()功能{ %h }返回浅哈希副本,而\%h返回对的引用%h(禁止复制)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Unblessing Perl 对象并为 Convert_blessed 构造 TO_JSON 方法 的相关文章

随机推荐