Obtaining a value from a nested hash/array data st

2019-09-13 03:02发布

问题:

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;

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

print $out{'b4'};

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'

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

回答1:

$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}.

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.

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.