use Data::Dumper; $Data::Dumper::Indent = 1; use Hash::Merge qw(merge); my @hashes = ( { '999' => { '998' => [ '908', '906', '0', '998', '907' ] } }, { '999' => { '991' => [ '913', '920', '918', '998', '916', '919', +'917', '915', '912', '914' ] } }, { '999' => { '996' => [] } }, { '999' => { '995' => [] } }, { '999' => { '994' => [] } }, { '999' => { '993' => [] } }, { '999' => { '997' => [ '986', '987', '990', '984', '989', '988' ] + } }, { '995' => { '101' => [] } }, { '995' => { '102' => [] } }, { '995' => { '103' => [] } }, { '995' => { '104' => [] } }, { '995' => { '105' => [] } }, { '995' => { '106' => [] } }, { '995' => { '107' => [] } }, { '994' => { '910' => [] } }, { '993' => { '909' => [] } }, { '993' => { '904' => [] } }, { '994' => { '985' => [] } }, { '994' => { '983' => [] } }, { '993' => { '902' => [] } }, { '999' => { '992' => [ '905' ] } }, ); sub arrayify_hashes { my ($hash) = @_; my @mapped; while (my ($key, $value) = each %{ $hash }) { push @mapped, { $key => ref($value) eq "HASH" ? arrayify_hashes($value) : $value }; } return \@mapped; } my $merged = pop(@hashes); for my $hash (@hashes) { $merged = merge($merged, $hash); } print Dumper arrayify_hashes($merged);
$VAR1 = [ { '993' => [ { '902' => [] }, { '904' => [] }, { '909' => [] } ] }, { '994' => [ { '910' => [] }, { '985' => [] }, { '983' => [] } ] }, { '999' => [ { '993' => [] }, { '994' => [] }, { '992' => [ '905' ] }, { '998' => [ '908', '906', '0', '998', '907' ] }, { '996' => [] }, { '997' => [ '986', '987', '990', '984', '989', '988' ] }, { '995' => [] }, { '991' => [ '913', '920', '918', '998', '916', '919', '917', '915', '912', '914' ] } ] }, { '995' => [ { '104' => [] }, { '103' => [] }, { '106' => [] }, { '102' => [] }, { '101' => [] }, { '105' => [] }, { '107' => [] } ] } ];
In reply to Re: Creating a tree-based hash out of hashes
by repellent
in thread Creating a tree-based hash out of hashes
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |