初学者对初学者的回答:)当然不应该像专业人士一样,但也许可以帮助你。
您写道:
我的猜测告诉我,一旦解码,对象将是与具有关键项目和数组引用作为值 一个元素的哈希值。
是的,它是一个散列,但decode_json
返回一个引用,在这种情况下,引用散列。 (从文档)
期望的UTF-8(二进制)串并尝试解析 作为UTF-8编码的JSON文本, 返回结果参考。
在您指派给标量变量的线
my $content = decode_json($json_str);
(未散列)。
因为你知道:这是一个参考,你可以做下:
printf "reftype:%s\n", ref($content);
#print: reftype:HASH ^
#therefore the +------- is a SCALAR value containing a reference to hash
这是一个hashref - 你可以转储所有按键
print "key: $_\n" for keys %{$content}; #or in short %$content
#prints: key: items
也可以assing的价值在 “项目”(数组引用)到一个标量变量
my $aref = $content->{items}; #$hashref->{key}
#or
#my $aref = ${$content}{items}; #$hash{key}
但NOT
#my $aref = $content{items}; #throws error if "use strict;"
#Global symbol "%content" requires explicit package name at script.pl line 20.
的$content{item}
从散列%content
请求值和你从未定义/分配这样的变量。 $content
是一个标量变量而不是散列变量%content
。
{
#in perl 5.20 you can also
use 5.020;
use experimental 'postderef';
print "key-postderef: $_\n" for keys $content->%*;
}
现在更深一步 - 对数组引用 - 你可以再次打印出的引用类型
printf "reftype:%s\n", ref($aref);
#reftype:ARRAY
打印数组的所有元素
print "arr-item: $_\n" for @{$aref};
却又不
#print "$_\n" for @aref;
#dies: Global symbol "@aref" requires explicit package name at script.pl line 37.
{
#in perl 5.20 you can also
use 5.020;
use experimental 'postderef';
print "aref-postderef: $_\n" for $aref->@*;
}
下面是一个简单的规则:
my @arr; #array variable
my $arr_ref = \@arr; #scalar - containing a reference to @arr
@{$arr_ref} is the same as @arr
^^^^^^^^^^ - array reference in curly brackets
如果你有一个$arrayref
- 使用@{$array_ref}
无处不在,你想使用数组。
my %hash; #hash variable
my $hash_ref = \%hash; #scalar - containing a reference to %hash
%{$hash_ref} is the same as %hash
^^^^^^^^^^^ - hash reference in curly brackets
如果你有一个$hash_ref
- 使用%{$hash_ref}
无处不在,你想使用的哈希值。
对于整个结构,以下
say $content->{items}->[0];
say $content->{items}[0];
say ${$content}{items}->[0];
say ${$content}{items}[0];
say ${$content->{items}}[0];
say ${${$content}{items}}[0];
打印相同值1
。
阅读[perlreftut](http://perldoc.perl.org/perlreftut.html)了解有关参考文献及其用法的信息。 – 2014-09-20 16:00:00
你的第一个问题是没有严格使用'',这会导致你的错误。 – cjm 2014-09-20 18:04:12
Re“Wny does'$ content {'items'}'不返回数组引用吗?”因为您从未将任何内容分配给该变量“%content”。 – ikegami 2014-09-20 18:09:35