如何访问存储在Hash中的数据

Jay*_*ley 5 perl json

我有这个代码:

$coder = JSON::XS->new->utf8->pretty->allow_nonref;
%perl = $coder->decode ($json);
Run Code Online (Sandbox Code Playgroud)

当我写print %perl变量时,它说HASH(0x9e04db0).如何访问此HASH中的数据?

Eug*_*ash 13

由于该decode方法实际上返回对hash 的引用,因此分配的正确方法是:

%perl = %{ $coder->decode ($json) };
Run Code Online (Sandbox Code Playgroud)

也就是说,要从哈希中获取数据,您可以使用每个内置或循环其键,并通过下标来检索值.

while (my ($key, $value) = each %perl) {
    print "$key = $value\n";
}

for my $key (keys %perl) {
    print "$key = $perl{$key}\n";
} 
Run Code Online (Sandbox Code Playgroud)


Leo*_*ans 7

JSON :: XS-> decode返回对数组或散列的引用.要做你想做的事,你必须这样做:

$coder = JSON::XS->new->utf8->pretty->allow_nonref;
$perl = $coder->decode ($json);

print %{$perl};
Run Code Online (Sandbox Code Playgroud)

换句话说,您在使用时必须取消引用哈希.


hob*_*bbs 5

返回值decode不是哈希值,你不应该将它赋值给%hash- 当你这样做时,你会破坏它的值.它是一个哈希引用,应该分配给标量.阅读perlreftut.