in reply to Use of Tree::Parser
If you are starting with a flat hash (or hash of arrays) and you want to build a tree-style hash, the basic plan would be to turn it into a recursive HoH structure, such that every "leaf" node in the tree is just an empty hash ref. Something like:
That includes a "parent" element for every node that has one or more parents, to make it easier to keep track of relations. I'm not sure if that's what you're looking for...use strict; use warnings; use Data::Dumper 'Dumper'; my %tree; while (<DATA>) { chomp; next unless ( /^\s*(\d+)\s*=>\s*(.*)/ ); my ( $key, $val ) = ( $1, $2 ); if ( $val eq '' ) { # leaf node $tree{$key} = {} unless exists( $tree{$key} ); # assign an em +pty hash ref } else { for my $node ( split /, +/, $val ) { if ( ! exists( $tree{$node} )) { $tree{$node} = {}; } $tree{$key}{$node} = \$tree{$node}; push @{$tree{$node}{parent}}, $key; # keep track of node paren +ts } } } # all done: for ( sort keys %tree ) { print "======\n$_:\n", Dumper( $tree{$_} ) unless exists( $tree{$_ +}{parent} ); } # append your data below... __DATA__
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Use of Tree::Parser
by Generoso (Prior) on Jun 01, 2010 at 22:30 UTC |