in reply to Tree in perl with hashes

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' => {} } } };

Replies are listed 'Best First'.
Re: Re: Tree in perl with hashes
by RuneK (Sexton) on May 06, 2004 at 11:58 UTC
    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