
naven8
Novice
Feb 24, 2012, 6:27 AM
Post #6 of 9
(1170 views)
|
|
Re: [hem] Accessing hash with dynamic keys
[In reply to]
|
Can't Post
|
|
I strictly dont recommend the following code.It will work only when you have only 1 key for the inner hash. All elements are seperated by "END" in the array.
use strict; use warnings; my @arr; my %hash = ('a0' => {'b0' => 'c0',}, 'a1' => 'b1', 'a2' => {'b2' => {'c2' => 'd2'},}, ); my $hash_ref = \%hash; foreach my $ke (sort(keys(%hash))){ func($hash_ref,$ke); } sub func { my $ref =shift; my $ke = shift; if (ref($ref->{$ke}) =~ /HASH/){ push(@arr,$ke); foreach my $ke_2 (sort(keys(%{$ref->{$ke}}))){ func(\%{$ref->{$ke}},$ke_2); } } else{ push (@arr,$ke); push (@arr,$ref->{$ke}); push (@arr,"END"); return; } } print "@arr";
(This post was edited by naven8 on Feb 24, 2012, 6:28 AM)
|