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

Hi all, I'm trying to create a simple tree from hashes. A node cosists of a name and one node can have x children and so on. Does someone have any example code for: - Node - Traverse - Insert Thanks, Rune

Replies are listed 'Best First'.
Re: Tree in perl with hashes
by bart (Canon) on May 06, 2004 at 09:30 UTC
    Try something like this for a basic node:
    $node = { name => 'foo', children => [], };
    This particular node has the name "foo" and no children. Adding a child to it, can be done like this:
    push @{$parent->{children}}, $child;
    where both parent and child are nodes set up as above.

    Use Data::Dumper (/me looks sideways to demerphq for his reaction) to see what's in your tree, for experimentation.

    Of course you're free to add more fields to a node, to hold the actual data.

Re: Tree in perl with hashes
by grinder (Bishop) on May 06, 2004 at 10:47 UTC

    The following is a fairly simple-minded technique for building the tree and performing preorder and postorder traversals.

    #! /usr/bin/perl -w use strict; use Data::Dumper; $Data::Dumper::Indent = 1; my %tree; while( <DATA> ) { chomp; my $t = \%tree; my @char = split //; for( @char ) { $t->{$_} = {} unless exists $t->{$_}; $t = \%{$t->{$_}}; } } sub pre_traverse { my $t = shift; for my $k( sort keys %$t ) { print "$k "; pre_traverse( $t->{$k} ); } } sub post_traverse { my $t = shift; for my $k( sort keys %$t ) { post_traverse( $t->{$k} ); print "$k "; } } print "PRE: "; pre_traverse(\%tree), print "\nPOST: "; post_traverse(\%tree), print "\n", Dumper(\%tree), "\n"; __DATA__ aB1 aB2 aB4j aB8 aC3 aC50

    This produces the following:

    PRE: a B 1 2 4 j 8 C 3 5 0 POST: 1 2 j 4 8 B 3 0 5 C a $VAR1 = { 'a' => { 'C' => { '3' => {}, '5' => { '0' => {} } }, 'B' => { '8' => {}, '4' => { 'j' => {} }, '1' => {}, '2' => {} } } };
      Thanks for the many answers, but I'm a bit confused. Here's the problem: I'm trying to traverse a version tree in a SCM tool (Continuus). Since you can only traverse 1 level at a time. So I run a command like this:
      my $tree = { name => undef, children => [], }; foreach (`command($tree->{name})`){ pseudo: add $_ to children[] for this $tree->{name}; } pseudo add all the childrens children.
      Could you please give an newbie example?
      Thanks,
      Rune
Re: Tree in perl with hashes
by edan (Curate) on May 06, 2004 at 09:49 UTC

    You can probably find lots of sample code by searching CPAN for Tree::

    --
    edan