What if you were to turn this around a bit and not order the datastructure but added an element that preserved the order?

My idea would be to have the primary data structure look something like this and keyed by the node id.

my %created = ( AUTHOR => $author, TYPE => $node_type, TIME => $node_time, PARENT => $parent_id || '', KIDS => [], );
One pass will load the structure from the data stream. A second pass will populate the KIDS array something like this. If the datastream is in order, or you are willing to assume that any referenced parent node will be included in the stream, you could actually include this in the first pass and save a loop. Personally, I prefer to keep the data acquisition loop seperate from the data manipulation loop - it makes it easier to debug.
for my $root ( sort { $a <=> $b } keys %created ) { my $parent = $created{$root}{PARENT}; push @{$created{$parent}{KIDS}}, $root; }
One final loop, then, can print out all the nodes in, hopefully a hierchical order by using a bit of recursion ( breadth-first? )
sub print_nodes { my @kids = @_; for my $id ( @nodes ) { print "Interesting data from node\n"; if ( @{$created{$id}{KIDS} ) { print_nodes( @{$created{$id}{KIDS}; } } } # Some work to make sure we start at the parents and move # our way down correctly. grep would work just as well. my @topnodes = (); for my $id ( keys %created ) { push @topnodes, $id unless ( defined( $created{$id}{PARENT} ) ); } print_nodes( @topnodes );
mikfire

In reply to Re: threaded display of replies by mikfire
in thread threaded display of replies by epoptai

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.