user1700494
user1700494

Reputation: 211

Perl. Hash inside array inside hash. How to get values of inner hash?

There is a simple code to query storm api

#!/usr/bin/env perl
use strict;
use warnings;
use HTTP::Request;
use LWP::UserAgent;
use LWP::Simple;
use JSON::XS;
use Try::Tiny;
use Data::Dumper;

my $ua = LWP::UserAgent->new; 
my $status = $ua->get("http://lab7.local:8888/api/v1/topology/summary");
my $sts = $status->decoded_content;
my $coder = JSON::XS->new->ascii->pretty->allow_nonref;
my $out = try {my $output = $coder->decode($sts)} catch {undef};
print Dumper(\%$out);

The output

$VAR1 = {
      'topologies' => [
                        {
                          'encodedId' => 'subscriptions_lab_product-8-1452610838',
                          'workersTotal' => 1,
                          'status' => 'ACTIVE',
                          'uptime' => '35m 54s',
                          'name' => 'subscriptions_lab_product',
                          'id' => 'subscriptions_lab_product-8-1452610838',
                          'tasksTotal' => 342,
                          'executorsTotal' => 342
                        }
                      ]
    };

How can i get for example the 'id' value of inner hash?
OS: RHEL6.6
Perl: 5.10.1

Upvotes: 1

Views: 540

Answers (2)

simbabque
simbabque

Reputation: 54323

If there is only one topology, it's simply what @MattJacob already said in his comment.

$out->{topologies}->[0]->{id}

If there are more, you can iterate.

my @ids;
foreach my $topology ( @{ $out->{topologies} } ) {
  push @ids, $topology->{id};
}

Here is a visual explanation including free-hand circles.

enter image description here

First there is a hash reference that only has the single key topologies.

$out->{topologies};

Under that key, there is an array reference. The elements in that array reference are hash references, but there is only one. To get that first one, use the index 0.

$out->{topologies}->[0];

Now you've got that hash reference with all the properties of the topology inside. You can use the key id to get the string on the right hand side of the dump.

$out->{topologies}->[0]->{id};

Also see perlreftut.

Upvotes: 3

Matt Jacob
Matt Jacob

Reputation: 6553

To answer your specific question, you need to use the dereference operator (->):

$out->{topologies}->[0]->{id}

Technically, the arrow is optional between subscripts, so the line above could be rewritten as:

$out->{topologies}[0]{id}

But since you're asking the question in the first place, I would recommend reading perldsc, perlref, and perlreftut to get a solid foundation for references in Perl.

Upvotes: 3

Related Questions