0

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?

lollan
  • 71
  • 5

1 Answers1

2

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

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • Schwern, this is great help and answers my question. Thank you! If I may ask one further question, if I want to iterate through the hash multiple times and obtain value 'B4' from multiple 'A4' hashes, how would I do that? The below works by statically defining a range of [0..8] but I would like for it to iterate through each hash and grab the 'B4' output programatically. for my $slice (0..8) { my $out = $out->{data}[$slice]{wwpn}; print " $out \n"; } – lollan Mar 01 '16 at 13:17
  • @lollan That would be best handled by asking another Stack Overflow question. – Schwern Mar 01 '16 at 18:47
  • Thanks again! http://stackoverflow.com/questions/35734341/iterating-through-a-hash-of-hashes – lollan Mar 01 '16 at 21:55