【发布时间】:2011-01-22 05:24:07
【问题描述】:
我有这个代码:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
%perl = $coder->decode ($json);
当我写 print %perl 变量时,它显示 HASH(0x9e04db0)。如何访问此 HASH 中的数据?
【问题讨论】:
我有这个代码:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
%perl = $coder->decode ($json);
当我写 print %perl 变量时,它显示 HASH(0x9e04db0)。如何访问此 HASH 中的数据?
【问题讨论】:
由于decode 方法实际上返回一个引用 来散列,正确的分配方法是:
%perl = %{ $coder->decode ($json) };
也就是说,要从哈希中获取数据,您可以使用 each 内置函数或遍历其键并通过下标检索值。
while (my ($key, $value) = each %perl) {
print "$key = $value\n";
}
for my $key (keys %perl) {
print "$key = $perl{$key}\n";
}
【讨论】:
JSON::XS->decode 返回对数组或散列的引用。要做你想做的事,你必须这样做:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
$perl = $coder->decode ($json);
print %{$perl};
换句话说,您必须在使用哈希时取消引用它。
【讨论】:
decode 的返回值不是哈希值,您不应该将其分配给 %hash —— 当您这样做时,您会破坏它的值。它是一个散列reference,应该分配给一个标量。阅读perlreftut。
【讨论】:
您需要指定哈希的特定键,然后只有您才能访问哈希中的数据。
例如,如果 %perl hash 有名为 'file' 的键;
你想像下面这样访问
打印 $perl{'file'} ; # 它会打印 %perl 哈希的文件键值
【讨论】:
方法很多,你可以用foreach loop
foreach my $key (%perl)
{
print "$key is $perl{$key}\n";
}
或while loop
while (my ($key, $value) = each %perl)
{
print "$key is $perl{$key}\n";
}
【讨论】: