#!/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