当请求arrayref时,perl中绑定哈希的奇怪行为 [英] Strange behavior of a tied hash in perl, when asking for an arrayref

查看:124
本文介绍了当请求arrayref时,perl中绑定哈希的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按照跟踪变量使用的顺序绑定一个哈希(或hashref).

I was trying to tie an hash (or hashref) in order of tracking variable usages.

一切都适用于简单的情况,但是当我尝试在某些真实代码上使用我的模块时,出现此错误:

Everything is working for simple cases, but when I tried to use my module on some real code I had this error:

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)

我使用以下代码复制了错误:

I've replicated the error using the following code:

use Tie::Hash::Usages;
use JSON;

my @arr = (
    {
        key1 => "ac",
        key2 => 12,
        key3 => 12
    },        
);
my %tied_hash;


tie %tied_hash, 'Tie::Hash::Usages';

$tied_hash{key1} = \@arr;

my @val = $tied_hash{key1};
print encode_json(\@val)."\n\n"; #this works

print encode_json($tied_hash{key1}); #this doesn't

相同的代码适用于普通哈希.

The same code works with a plain hash.

在第二种情况下,我也需要这样做,因为代码库很大,我不想更改它,或者因为怀疑某些地方在某些情况下无法工作而感到怀疑.

I'd need this to work also in the second case, the code base is huge and I don't want to change it or live with the doubt that something somewhere will not work in some particular case.

package Tie::Hash::Usages;
use strict;
use warnings;

use Tie::Hash;

use vars qw(@ISA);

@ISA = qw(Tie::StdHash);

sub TIEHASH {

    my ($class, $tracker, $filename) = @_;
    my %hash;

    bless \%hash, $class;

}

sub STORE {
    my ($self, $key, $val) = @_;
    $self->{$key} = $val;
}

sub DELETE {
    my ($self, $key) = @_;
    delete $self->{$key};

}

sub FETCH {
    my ($self, $key) = @_;
    return $self->{$key};
}

sub DESTROY {
    my $self = shift;
}
1;

perl版本:v5.18.2

perl version: v5.18.2

推荐答案

最小演示:

use JSON::XS  qw( encode_json );
use Tie::Hash qw( );

our @ISA = 'Tie::StdHash';

{
   tie my %tied, __PACKAGE__;
   $tied{data} = { a => 1 };
   encode_json($tied{data});  # Exception: hash- or arrayref expected ...
}

JSON是JSON :: PP(默认)或JSON :: XS(如果找到)的前端.这是JSON :: XS的问题.

JSON is a front-end for JSON::PP (default) or JSON::XS (if found). This is a problem with JSON::XS.

许多XS代码不处理魔术变量(这是$tied{EXPR}返回的内容),而JSON :: XS自1.2版以来已处理了魔术值,但它并不用于直接传递给.

A lot of XS code doesn't handle magical variables (which is what $tied{EXPR} returns), and while JSON::XS has handled magical values since version 1.2, it doesn't for the value directly passed to encode_json.

这是JSON :: XS中的现有错误,可以通过以下方法解决:

This is an existing bug in JSON::XS that can be worked around as follows:

encode_json(my $non_magical = $tied{data})

错误已报告.

这篇关于当请求arrayref时,perl中绑定哈希的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆