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

Hello, I am attempting to process data in a tree where, for example, "D" is the child of "C", "C" is the child of "B", and so on all the way back to "A".

Represented another way, the path to "D" is A/B/C/.

My goal is to create a subroutine that would return the path to whatever child I passed to the subroutine. So, once again, if I passed "D" to the subroutine, it would return "A/B/C/". I have approached this task by creating two hashes that share the same keys:

my %name = (1, "A", 2, "B", 3, "C", 4, "D"); my %parent = (1, 0, 2, 1, 3, 2, 4, 3);
I have also created a subroutine to return the value from the "name" hash for the parent of a child:
sub get_parent_value { my $parent_key = $parent{$key}; my $parent_value = $name{$parent_key}; return $parent_value; }
I am now uncertain how to create a loop that will keep passing the key of the child's parent to the subroutine until the parent of the parent is "0".

I would love to see any ideas you all might have on this.

Thanks for your time!

Replies are listed 'Best First'.
Re: Processing Data in a Tree
by dragonchild (Archbishop) on Jun 26, 2008 at 01:33 UTC
    Take a look at Tree and the traverse() method, specifically the child-first option. You can then keep track of the path down to the node in a stack and just stop traversing when you hit the node you care about.

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: Processing Data in a Tree
by Limbic~Region (Chancellor) on Jun 26, 2008 at 01:45 UTC
    reluctant_techie,
    Assuming you have a get_parent() that works, it should be as simple as:
    sub get_path_from_root { my ($node) = @_; my @path; while (my $parent = get_parent($node)) { unshift @path, $parent; $node = $parent; } return join '/', @path; }

    Cheers - L~R

Re: Processing Data in a Tree
by jethro (Monsignor) on Jun 26, 2008 at 02:35 UTC
    I assume there is a reason for the numbers? Otherwise you could just store names as keys and values, i.e. you would need only one hash
    my %parent = ('A',0,'B','A','C',B','D','C';
    That way keys %parent would give you a list of all names (as substitute for the names hash). If you don't need that, the hash entry ('A',0) could be dropped and not exists $parent($x) would be true if $x has no parent.

    But if you need the numbers, there is still one thing I would change: get_parent_value should return the number of the parent and not the name (as long as it is fed the number of the child and not the name). It is not good design to continually switch between different representations of the same thing. You're sure to mix them up eventually and get a number when you expected a name or vice versa in your code

    By the way, your sub is missing a first line my ($key)=@_;