佩尔。散列内部数组内部散列。如何获取内部哈希值?

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

查询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);

输出

$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
                        }
                      ]
    };

我怎样才能得到例如内部散列的 'id' 值?
OS: RHEL6.6
Perl:5.10.1

如果只有一种拓扑结构,那就是.

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

如果多了可以迭代

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

这是一个直观的解释,包括 free-hand 个圆圈。

首先有一个哈希引用,它只有一个键 topologies

$out->{topologies};

在该键下,有一个数组引用。该数组引用中的元素是散列引用,但只有一个。要获得第一个,请使用索引 0.

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

现在您已经获得了包含内部拓扑所有属性的散列引用。您可以使用键 id 来获取转储右侧的字符串。

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

另见 perlreftut

要回答您的具体问题,您需要使用 dereference operator (->):

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

从技术上讲,下标之间的箭头是可选的,因此上面的行可以重写为:

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

但是既然你一开始就问这个问题,我建议你阅读 perldsc, perlref, and perlreftut 来为 Perl 的参考打下坚实的基础。