I've written something like this a couple of times, here's a do-your-own-recursion recipee:
use Tree::DAG_Node; use Data::Dumper; local $Data::Dumper::Indent=1; use strict; use warnings; my $t = tits( \*DATA ); #print Dumper( $t ),$/; print Dumper( $t->tree_to_lol ), $/; print map { "$_\n" } @{$t->draw_ascii_tree}; sub tits { my( $fh, $d ) = @_; $d ||= 2; my @t = Tree::DAG_Node->new(); my $depth = 0; my @pdepth = 0; while(defined( $_ = readline $fh )){ chomp; if(/\A((?:\s{$d})+)(.*)\z/){ $depth = length $1; if( $depth > $pdepth[-1] ){ my $newd = $t[-1]->new_daughter({ name => $2 }); push @t, $newd; push @pdepth, $depth; } elsif( $depth == $pdepth[-1] ){ $t[-1]->new_daughter({ name => $2 }); } else { pop @t; pop @pdepth; } } else { # should only happen at root (depth/pdepth both 0) $t[0]->name($_); } $depth = $pdepth[-1]; } return $t[0]; } __DATA__ Building House Window Glas Silicium Door Roof Wood Hut Pizza Garage Door
update1: whooooops, as you can see, Hut , Door and Roof are missing, and Pizza is a child of Window. IGNORE$VAR1 = [ [ [ [ [ 'Silicium' ], 'Glas' ], [ 'Wood' ], [ 'Pizza' ], 'Window' ], [ 'Door' ], 'House' ], 'Building' ]; | <Building> | <House> /---------------\ | | <Window> <Door> /--------+-------\ | | | <Glas> <Wood> <Pizza> | <Silicium>
update3: seeing how i got ++ed besides this code being broken, here it is, fixed up (i also added readmore tags, made clear which update was which):
use Tree::DAG_Node; use Data::Dumper; local $Data::Dumper::Indent=1; use strict; use warnings; my $t = tits( \*DATA ); #print Dumper( $t ),$/; print Dumper( $t->tree_to_lol ), $/; print map { "$_\n" } @{$t->draw_ascii_tree}; sub tits { my( $fh, $d ) = @_; $d ||= 2; my @t = Tree::DAG_Node->new(); my $depth = 0; my $pdepth = 0; while(defined( $_ = readline $fh )){ chomp; if(/\A((?:\s{$d})+)(.*)\z/){ $depth = length($1)/$d; if( $depth > $pdepth ){ push @t, $t[-1]->new_daughter({ name => $2 }); } elsif( $depth == $pdepth ){ $t[-1] = $t[-1]->mother->new_daughter({ name => $2 }); } else { pop @t until @t == $depth; push @t, $t[-1]->new_daughter({ name => $2 }); } } else { # should only happen at root (depth/pdepth both 0) $t[0]->name($_); } $pdepth = $depth; } return $t[0]; } __DATA__ Building House Window Glas Silicium Door Roof Wood Hut Pizza Garage Door
$VAR1 = [
[
[
[
[
'Silicium'
],
'Glas'
],
'Window'
],
[
'Door'
],
[
[
'Wood'
],
'Roof'
],
'House'
],
[
[
'Pizza'
],
'Hut'
],
[
[
'Door'
],
'Garage'
],
'Building'
];
|
<Building>
/----------------+-------\
| | |
<House> <Hut> <Garage>
/--------+------\ | |
| | | <Pizza> <Door>
<Window> <Door> <Roof>
| |
<Glas> <Wood>
|
<Silicium>
In reply to Re: tree in hash
by PodMaster
in thread tree in hash
by Murcia
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |