Perl访问哈希中的哈希并循环遍历每个哈希以提取值

时间:2011-08-26 19:43:46

标签: perl hash

我正在尝试访问哈希中的哈希并循环遍历它以获取值。这是数据的一个例子

$VAR1 = {
      '24.40.53.143' => {
                          'ServStat' => {
                                          '1.18.118.115.95.99.119.98.98.112.109.45.97.112.95.104.116.116.112.115' => 'vs_cgggbpm-ap_https',
                                          '1.17.118.115.95.99.119.98.115.102.97.45.97.112.95.104.116.116.112' => 'vs_cddedsfa-ap_http',
                                          '20.18.118.115.95.99.119.98.116.119.98.45.98.112.95.104.116.116.112.115' => '0',
                                          '19.17.118.115.95.99.119.98.119.115.45.97.112.95.104.116.116.112.115' => '0',
                                          '2.18.118.115.95.99.119.98.116.119.98.45.98.112.95.104.116.116.112.115' => '0',
                                          '24.18.118.115.95.99.119.98.116.119.98.45.97.112.95.104.116.116.112.115' => '0',
                                          '17.17.118.115.95.99.119.98.119.98.45.97.112.95.104.116.116.112.115' => '0',
                                          '29.17.118.115.95.99.119.98.116.119.112.45.98.112.95.104.116.116.112' => '0',  

我想遍历'ServStat'并提取每个值。我如何引用散列'ServStat'以便我可以对内容进行预测?像这样:

foreach {ServStat} {
my ( $num, $char, $vs ) = (/(\d+)\.(\d+)\.(.+)/ );
if ($num == 1) { 
print {ServStat}->$value
}
}  

提前感谢您提供任何建议!

1 个答案:

答案 0 :(得分:2)

要获取密钥,您可以在哈希上使用函数keys

my $data = {
      '24.40.53.143' => {
                          'ServStat' => {'1.18.118.115.95.99.119.98.98.112.109.45.97.112.95.104.116.116.112.115' => 'vs_cgggbpm-ap_https'}
      }
};


my $ServStat = $data->{24.40.53.143}{ServStat};

foreach my $key (keys %{$ServStat}) { # you need the {} to dereference as $ServStat is a hash reference
 ...#Now, in $key, you have the key 1.18.118.115.95.99.119.98.98.112.109.45.97.112.95.104.116.116.112.115

}  

如果您只想要所有值,只需在哈希

上使用函数values
my @values = values %{$ServStat};