Here's some code that works for your test data. There's an obvious bug (infinite recursion if there's a loop in your data): I'm sure you can solve that yourself.
$hash{"0"}=["1","2","15"];
$hash{"1"}=["3","4"];
$hash{"2"}=["5","6"];
$hash{"3"}=["7","8"];
sub expand
{
my ($key) = @_;
if (exists $hash{$key})
{
return sort { $a <=> $b } $key, map { expand($_) } @{$ha
+sh{$key}}
}
else
{
return $key
}
}
my @expanded = map {[ expand $_ ]} @{$hash{0}};
use Data::Dumper;
print Dumper(\@expanded);
--Dave
Update: I've just realised that the if (exists ...) check is not needed: if the key doesn't exist, then an empty array will be used, automagically. so the expand function becomes:
sub expand
{
my ($key) = @_;
return sort { $a <=> $b } $key, map { expand($_) } @{$hash{$ke
+y}}
}
Update 2: For efficiency, you probably want to move the
sort outside the loop!
Update 3: For the golfers amongst us:
sub e{@_,map{e($_)}@{@hash{@_}}}
print Dumper[map{[sort{$a<=>$b}e$_]}@{$hash{0}}]
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.