Perl从哈希中提取数据

时间:2015-05-21 12:08:22

标签: perl hash

我正在尝试从哈希值中提取数据。

   my $triggers = $zabbix->raw('trigger','get', $options);
   print Dumper($triggers);

    foreach my $trigger (@{$triggers} )
    {

    push @triggerid,$trigger->{'triggerid'};

    my @t=$trigger->{'hosts'};
    my $lt = localtime($trigger->{'lastchange'});
    print "$trigger->{'description'} $lt \n";

    }

Dumper的输出

[
   {
        'hosts' => [
                     {
                       'hostid' => '19914',
                       'host' => 'pc10bcf18.syd.sf.priv'
                     }
                   ],
        'priority' => '2',
        'status' => '0',
        'templateid' => '10652913',
        'comments' => '',
        'state' => '0',
        'triggerid' => '10653191',
        'expression' => '{15070357}#1',
        'error' => '',
        'url' => '',
        'flags' => '0',
        'value' => '1',
        'name' => 'pc10_BizX_A_CF',
        'description' => 'pc10bcf18.syd.sf.priv: Core Path not \'/dumps/java/core\' (Path=/export/home/jboss/j...)',
        'value_flags' => '0',
        'lastchange' => '1429181103',
        'type' => '0'
      },
]          

根据我的上述代码,我能够打印' description'。如何访问和打印“主持人”的价值?值?

3 个答案:

答案 0 :(得分:1)

看起来可以有多个主机,所以

my @hosts =
   map { $_->{host} }
      @{ $trigger->{hosts} };

要获得第一个(假设总是至少有一个),

my $first_host = $trigger->{hosts}[0]{host};

答案 1 :(得分:1)

要维护您已编码的for / push模式,您可以写这个

my $triggers = $zabbix->raw('trigger', 'get', $options);

my @triggerid;

for my $trigger ( @$triggers ) {

  push @triggerid, $trigger->{triggerid};

  my @hosts;
  my $hosts = $trigger->{hosts};
  for my $host ( @$hosts ) {
    push @hosts, $host->{host};
  }

  my $lt = localtime($trigger->{lastchange});
  print "$trigger->{description} $lt\n";
}

答案 2 :(得分:-1)

$triggers->{'hosts'}->[0]->{'host'}