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; } }

In reply to Re: Building an object tree by mirod
in thread Building an object tree by Beatnik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.