Recursion is expensive, but sometimes it's the quickest solution. Never one to walk away from a programming challenge (that I can actually envision), here's what you have to do to get at all of the keys in a Hash of Hashes of indeterminate nesting.
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;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.