我不明白为什么这个解决方案有效,而我自己没有.我的问题在下面重述
my $json_raw = getJSON(); my $content = decode_json($json_raw); print Data::Dumper($content);
此时我的JSON数据已经转化为此
$VAR1 = { 'items' => [ 1,2,3,4 ] };
我的猜测告诉我,一旦解码,该对象将是一个散列,其中一个元素具有关键项和数组引用作为值.
$content{'items'}[0]
其中$content {‘items’}将获得数组引用,而外部$… [0]将访问数组中的第一个元素并将其解释为标量.但这不起作用.我收到一条使用未初始化值的错误消息[…]
但是,以下工作正常:
$content->{items}[0]
其中$content-> {items}产生数组引用,[0]访问该数组的第一个元素.
问题
>为什么$content {‘items’}不返回数组引用?我甚至试过@ {content {‘items’}},认为一旦我从内容{‘items’}获得了值,就需要将其解释为数组.但是,我仍然收到未初始化的数组引用.
>如何在不使用箭头运算符的情况下访问数组引用?
解决方法
use strict; #use this all times use warnings; #this too - helps a lot! use JSON; my $json_str = ' { "items" : [ 1,4 ] } '; my $content = decode_json($json_str);
你写了:
My guess tells me that,once decoded,the object will be a hash with
one element that has the key items and an array reference as the value.
是的,它是一个散列,但是decode_json返回一个引用,在本例中是对hash的引用. (来自文档)
expects an UTF-8 (binary) string and tries to parse that
as an UTF-8 encoded JSON text,
returning the resulting reference.
在线
my $content = decode_json($json_str);
您分配给SCALAR变量(不是哈希).
因为你知道:它是一个参考,你可以做下一个:
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
你也可以将“items”(arrayref)的值赋给标量变量
my $aref = $content->{items}; #$hashref->{key} #or #my $aref = ${$content}{items}; #$hash{key}
但不是
#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.
{ #in perl 5.20 you can also use 5.020; use experimental 'postderef'; print "key-postderef: $_\n" for keys $content->%*; }
现在再深入 – 到arrayref – 再次打印出引用类型
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。