The sort is optional, as is what you do with the keys and values, once you find them. Making this into a subroutine and changing the output appropriately is left as an exercise for the reader.
#!/usr/bin/perl -w use strict; my %hash = ( 1 => 1, 2 => { 3 => 4, 5 => { 6 => 7 }, }, 8 => 9, 10 => {}, ); my @stack; push @stack, \%hash; my $tree = ''; my $level = 0; while (@stack) { my ($hash_ref, $keys_ref); if (ref($stack[-1]) eq 'ARRAY') { ($hash_ref, $keys_ref) = @{ pop @stack }; $level--; } else { $hash_ref = pop @stack; $keys_ref = [ sort { $b <=> $a } (keys %$hash_ref) ]; } while (my $key = pop @{ $keys_ref }) { my $value = $hash_ref->{$key}; if (ref($value) eq 'HASH') { $tree .= "\t" x $level . "$key => \n"; push @stack, ([ $hash_ref, $keys_ref ], $value); $level++; last; } else { $tree .= "\t" x $level . "$key => $value\n"; # print "on key $key, stack is ", $level, " levels deep.\n" +; } } } print $tree;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Iterate over HoH without Recursion
by ZZamboni (Curate) on May 21, 2000 at 04:59 UTC | |
by tphyahoo (Vicar) on Nov 24, 2005 at 15:02 UTC |