【发布时间】:2016-06-17 07:27:11
【问题描述】:
#!/usr/bin/perl
use strict;
use warnings;
my %ani_hash = (
'machine_results' => [
{
'status' => 'Failed install',
'machine' => '23.73.134.235',
'seconds' => '20',
'try' => '1'
},
{
'status' => 'Failed install',
'machine' => '23.73.134.140',
'seconds' => '20',
'try' => '1'
}
],
'description' => 'MC-5897'
);
get_elements( \%ani_hash );
sub get_elements
{
my $hashref1 = shift;
my %hashref2 = %$hashref1;
print "%hashref1\n";
foreach my $machineresult ( keys %hashref2 ) {
foreach my $machineresult2 ( keys %{ $hashref2{$machineresult} } ) {
print "$hashref2{$machineresult}{$machineresult2}\n";
}
}
}
Output:
HASH(0x1e9fe58)
Not a HASH reference at ./hashref.pl line 62.
Can't use string ("MC-5897") as a HASH ref while "strict refs" in use at ./hashref.pl line 62.
我想遍历所有键值对并获取它们的值。 我不想使用 dumper 方法来获取值,我想通过循环方法来获取这些值。任何帮助,将不胜感激。谢谢
我这样做是为了解决问题并获取“machine_results”的内容。
print "description: $hashref2{description}\n";
foreach my $machineresult( sort keys%hashref2){
foreach my $array (@{ $hashref2{$machineresult} }){
foreach my $array1( sort keys%{$array} ){
print "key is $array1 and it's value is $array->{$array1}`",
"enter code here`\n";
}
print "\n";
}
}
【问题讨论】:
-
$hashref2{$machineresult}是对数组的引用,所以keys %{ $hashref2{$machineresult} }没有意义。你想要@{ $hashref2{$machineresult} } -
在我看来,你的
%ani_hash总是有 2 个元素,machine_results和description,而你只想遍历数组(参考)machine_results,对吧? -
@DavidO:我对你的讽刺有疑问,以及暗示 recursion 是处理这种结构的唯一方法
-
感谢@ikegami 的帮助,我已经编辑了我的帖子。如果这看起来不错,请告诉我。
-
自己运行代码,你会看到
Can't use string ("MC-5897") as an ARRAY ref while "strict refs" in use at ./so.pl line 36.那就是foreach my $array。发生这种情况是因为代码试图将$hashref2{'description'}解释为不是的arrayref。这是一个字符串。