bryank has asked for the wisdom of the Perl Monks concerning the following question:
What I have been trying to do this morning is understand how the Tree::Simple module works specifically. I want to take an input file that contains a delimited file of child/parents, build a tree, and output a flattened version.
If I had:
the output would be:apple:fruit granny smith:apple rotten granny smith:granny smith . . . orange|fruit
Fruit:Apple:Granny Smith:Rotten Granny Smith Fruit:Orange
The example on the module page for Tree::Simple is helpful, but I am trying to figure out how to read in my input file. I am assuming I'd use a while loop. Any tips on tweaking the below code?
use warnings; use strict; use Tree::Simple; # make a tree root my $tree = Tree::Simple->new("0", Tree::Simple->ROOT); # explicity add a child to it $tree->addChild(Tree::Simple->new("1")); # specify the parent when creating # an instance and it adds the child implicity my $sub_tree = Tree::Simple->new("2", $tree); # chain method calls $tree->getChild(0)->addChild(Tree::Simple->new("1.1")); # add more than one child at a time $sub_tree->addChildren( Tree::Simple->new("2.1"), Tree::Simple->new("2.2") ); # add siblings $sub_tree->addSibling(Tree::Simple->new("3")); # insert children a specified index $sub_tree->insertChild(1, Tree::Simple->new("2.1a")); # clean up circular references $tree->DESTROY(); $tree->traverse(sub { my ($_tree) = @_; print (("\t" x $_tree->getDepth()), $_tree->getNodeValue(), "\n"); });
Here is what I have so far:
Output:use warnings; use strict; use Tree::Simple; my $tree = Tree::Simple->new("0", Tree::Simple->ROOT); while(<DATA>) { chomp; my ($child, $parent) = split ":"; my $sub_tree = Tree::Simple->new("$parent", $tree); $sub_tree->addChild(Tree::Simple->new("$child")); $tree->DESTROY(); } $tree->traverse(sub { my ($_tree) = @_; print (("\t" x $_tree->getDepth()), $_tree->getNodeValue(), "\n"); }); __DATA__ apple:fruit granny smith:apple rotten granny smith:granny smith orange:fruit
fruit apple apple granny smith granny smith rotten granny smith fruit orange
|
|---|