in reply to tree in hash
If you don't strictly need a nested-hash structure, and are willing to go more OO. You could use a module I created called Tree::Parser.
It parses many types of structured text into Tree::Simple object hierarchies. After that you can use Tree::Simple::VisitorFactory which supplies a number of Visitor object such as Breadth-first traversal, post-order traversal, gathering descendents, finding the path back to the root, etc. You can also use Tree::Simple::View to easily display your Tree::Simple object hierarchies in HTML and DHTML.
The Tree::Parser code to do this would look like:
The $input can be any number of things, including a single string (with embedded newlines), an array reference of lines from a file, etc (see the docs for more info). If your file uses tabs (\t) instead of spaces, then you can use the useTabIndentedFilters method instead, or even write your own custom filter, again, see the docs for more info.use Tree::Parser; my $tp = Tree::Parser->new($input); $tp->useSpaceIndentedFilters(2); my $tree = $tp->parse();
The $tree variable will be a Tree::Simple object hierachy. You can print it out easily with this:
You could also use Tree::Parser's deparse feature as well, which will write it back into the format it was parse from:$tree->traverse(sub { my ($t) = @_; print(("\t" x $t->getDepth()) . $t->getNodeValue() . "\n"); });
If you wanted to traverse your tree breadth-first, it is pretty simple to do with the BreadthFirstTraversal Visitor in Tree::Simple::VisitorFactory.my $deparsed_tree = $tp->deparse(); print $deparsed_tree; # or in array context you get an array of lines my @lines = $tp->deparse(); print join "\n" => @lines;
And if you needed to display your tree's in HTML or DHTML, you can use Tree::Simple::View to do that. This page contains a number of examples of the DHTML output, as well as the code used to create that output. We have tested the DHTML to work on most modern browsers (5.0+), and if you require support on earlier browsers, you can use the HTML output.use Tree::Simple::VisitorFactory; my $visitor = Tree::Simple::VisitorFactory->get("BreadthFirstTraversal +"); $tree->accept($visitor); print join ", " => $visitor->getResults(); # this prints : Building, House, Hut, Garage, Window, Door, Roof, Pizz +a, Door, Glas, Wood, Silicium
And of course, if you have any questions on these modules, you can either contact me here at PM, or you can email me.
|
|---|