in reply to Building an object tree
This is one way to build a tree-like structure, but there are others. My favorite is to have a complete tree, where each node has lonks to its parent, first and last child and previous and next sibling. Of course you then have to take care of circular references and provide a way to purge the tree, but in exchange you get ways to navigate the tree that are, I think, really convenient. In particular if you have a query language on the tree you really need to be able to go from a node to its neighbors. With the kind of tree you build in your example you are pretty much limited to traversing the entire tree any time you want to process any node. In the XML world you can look at the tree mode of XML::Parser or at XML::Simple for the kind of trees you are using, and at XML::DOM, XML::Twig and XML::XPath for the kind of tree I like. XML::XPath is especially interesting as it is based on Orchard, a tree manipulation module build in a C-like language that's supposed to be much faster than pure Perl.
Here is an example of how to build a "strongly linked" tree:
# This subroutine will adds a child as last child of parent: sub add_child { my( $parent, $child)= @_; my $prev_sibling= $parent->last_child; $child->{parent}= $parent; $parent->{last_child}= $child; $parent->{first_child}= $child unless( $parent->{first_child}); if( $prev_sibling) { $child->{prev_sibling}= $prev_sibling ; $prev_sibling->{next_sibling}= $child; } }
|
|---|