PhosphoricX has asked for the wisdom of the Perl Monks concerning the following question:

Oh wise Monks,

I'm parsing through a file with a tree structure. I would like to create an object that will store each of the entries found and then allow me to store all the entries within it, using a node structure. How can I setup my new constructor and addSubBlock methods to accomplish this?
---------------------------------------------------------
On Mar 30, 2004 at 14:08 GMT+1
Reworded question to make it easier to understand.

Replies are listed 'Best First'.
Re: List of Children Objects
by herveus (Prior) on Mar 30, 2004 at 12:35 UTC
    Howdy!

    Untested and (in part) schematic code follows:

    sub new { my $class = shift; my $self = { children => [] }; bless $self, $class; } sub addSubBlock # (newblock) { my $self = shift; my $block = shift; push @{$self->{children}}, $block; } sub traverse_preorder { my $self = shift; my @children = (); foreach my $child (@{$self->{children}) { push @children, $child, $child->traverse_preorder; } return @children; }

    OK, so I'm using a hash reference for the object data. I'm only using that for ease of illustration.

    Updated:renamed traverse_inorder to traverse_preorder. D'oh!

    yours,
    Michael
      Thanks for your reply, your code was what I was looking for.
Re: List of Children Objects
by simon.proctor (Vicar) on Mar 30, 2004 at 12:41 UTC
    You are making (if I read you correctly) a tree structure. Start with that. A tree is made of nodes and have links or branches to children and one to a parent (somewhat simplified but there you go). So without seeing more requirements I would say build a node object with an internal array of children (left is index 0). Then have a reference to your parent. If the parent is null thats your root.

    Adding a child would be as simple as creating the node and pushing onto the child list (again simplified). Iterating is more complicated so I suggest you read up on the topic.

    Algorithms in Perl covers a nice example of this plus you can google around for information on tree structures.
Re: List of Children Objects
by Happy-the-monk (Canon) on Mar 30, 2004 at 12:18 UTC
Re: List of Children Objects
by yuvalle1 (Initiate) on Mar 30, 2004 at 14:02 UTC
    If your file has the xml format, you may want to try XML::Simple which will probably do the work for you