从嵌套的散列/阵列获取的值 [英] Obtaining a value from a nested hash/array data structure

查看:126
本文介绍了从嵌套的散列/阵列获取的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的使用Perl和使用数据::自卸车打印的内容,希望指派几个键作为变量的一些API查询。

I am doing some API queries using Perl and using Data::Dumper to print the contents and hopefully assign several keys as variables.

   $client->request( "GET", "interfaces/detail", $opts );
    my $out = decode_json $client->responseContent();
    print Dumper $out;

不过,我无法打印特定键的(B4)输出,或将它定义为一个变量。

However, I am unable to print a specific key's (b4) output or define it as a variable.

print $out{'b4'};

我认为,这是由于JSON格式HASH /阵列/ HASH / HASH /键=>值的嵌套的数据结构。

I think that this is due to the nested data structure of HASH/ARRAY/HASH/HASH/Key=>Value in JSON format.

  DB<1> x $out
0  HASH(0x493f290)
   'data' => ARRAY(0x494e2e0)
      0  HASH(0x4475160)
         'a1' => '11'
         'a2' => '12'
         'a3' => '13'
         'a4' => HASH(0x494e560)
            'b1' => '21'
            'b2' => 22
            'b3' => '23'
            'b4' => '24'
            'b5' => '25'
            'b6' => '26'
            'b7' => '27'
         'a5' => '14'

我怎样才能从引用的布局得到值24?

How can I obtain the value "24" from the referenced layout?

推荐答案

$退出不是乱码,这是一个散列引用。如果你不知道在Perl引用,阅读的Perl参考教程。引用解除引用与 - &GT; 。取而代之的 $ {出关键} $输出方式&gt; {键}

$out is not a hash, it is a hash reference. If you're not sure about references in Perl, read the Perl Reference Tutorial. References are dereferenced with ->. Instead of $out{key} it is $out->{key}.

在特定的情况下,你有一个散列引用到列表的哈希与另一个哈希值。这些交易被覆盖在 Perl数据结构食谱。由于 B4 是几层下来,你需要指定每一层。 $输出方式&gt; {}数据[0] {A4} {B4}

In your specific case you have a hash reference to a list to a hash with another hash. Dealing with these is covered in the Perl Data Structures Cookbook. Since b4 is several layers down, you need to specify each layer. $out->{data}[0]{a4}{b4}.

$ {出关键} 正在访问的散列%了。该印记(即 $ @ )修改根据变量如何被使用的,但 $出{键} 还是%了

$out{key} is accessing the hash %out. The sigil (ie. $, @ and %) changes according to how the variable is being used, but $out{key} is still %out.

由于 $出{键} 访问一个不同的变量,你应该得到一个错误,如全局符号%去需要明确包名。不幸的是,Perl的默认情况下不这样做,你有来打开它使用严格。这应该是在你的程序顶端的第一件事情之一。 你应该真的,真的,真的使用严格和警告的。它会抓住很多令人沮丧的错误,赞一个。

Because $out{key} accesses a different variable, you should have gotten an error like Global symbol "%out" requires explicit package name. Unfortunately, Perl doesn't do this by default, you have to turn it on with use strict. This should be one of the first things at the top of your program. You should really, really, really use strict and warnings. It will catch many frustrating mistakes like this one.

这篇关于从嵌套的散列/阵列获取的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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