#!/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.
我要循环,并得到他们的价值观。 我不想使用自卸车方法来获取值,我想通过循环方法来获取这些值。任何帮助,将不胜感激。谢谢通过所有的键值对非关联嵌套的哈希在Perl
我这样做是为了解决这个问题并获取'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}}' – ikegami
它对我来说看起来你的'%ani_hash'总是有2个元素,'machine_results'和'description',而你只想遍历数组'machine_results',对吧? – PerlDuck
@DavidO:我有一个问题,你的讽刺,以及暗示,*递归*是处理这种结构的唯一方法 – Borodin