in reply to Re: walking a hash
in thread walking a hash
I have changed the code many times. Here is my latest attempt.$rh_dtree = { 'L1' => { 'L2b' => { 'L2b1' => {}, 'L2b2' => {} }, 'L2a' => { L3b' => { L4a' => {} }, L3a' => {} } }, 'L3b' => { 'L4a' => {} }, 'L2b' => { 'L2b1' => {}, 'L2b2' => {} }, 'L2a' => { 'L3b' => { 'L4a' => {} }, 'L3a' => {} } };
Main(); Main { my %dtree = init(); processDtree(\%dtree); } sub processDtree { my $rh_dtree = shift; foreach my $parent ( keys %{$rh_dtree} ) { my @nodenames = (); hash_walk( \%{$rh_dtree->{$parent}},[],\@nodenames); print join("\n",@nodenames) . "\n"; exit; } } sub hash_walk { my ($rh_dtree,$ra_keys,$ra_nodenames) = @_; while (my ($k, $v) = each %$rh_dtree) { # keep keys ordered. push(@$ra_keys,$k); if ( scalar keys %{$v} ) { hash_walk($v,$ra_keys,$ra_nodenames); } } push(@$ra_nodenames, join(".",@$ra_keys)); @$ra_keys = (); }
The output from running the follows: Note that I am exiting in the first iteration of the foreach loop in processDtree to make it easier to examine the output.
I would like to achieve this:L2b.L2b1 L2b.L2b1.L2b2 L2b.L2b1.L2b2 L2b.L2b1.L2b2.L2a.L3b.L4a L2b.L2b1.L2b2.L2a.L3b.L4a L2b.L2b1.L2b2.L2a.L3b.L4a.L3a L2b.L2b1.L2b2.L2a.L3b.L4a.L3a
nested-L2b nested-L2b.nested-L2b1 nested-L2b.nested-L2b2 nested-L2a nested-L2a.nested-L3b nested-L2a.nested-L3b.nested-L4a nested-L2a.nested-L3a
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: walking a hash
by GrandFather (Saint) on May 04, 2010 at 21:12 UTC |