in reply to trees and depth-first search

Something like this?

#! perl -slw use strict; $|=1; my $tree = { top => { inetUser => {}, person => { organizationalPerson => { managedPerson => { personnel => {}, }, }, }, application => { managedApplication => {}, }, }, }; sub explore; sub explore { my( $tree, $leaf ) = @_; for my $node ( keys %$tree ){ return $node if $node eq $leaf; next unless keys %{ $tree->{ $node } }; my @found = explore $tree->{ $node }, $leaf; return ( $node, @found ) if @found; } return; } printf "Looking for %-20s: %s\n", $_, join ' -> ', explore $tree, $_ for qw[ fred inetUser managedApplication personnel ]; __END__ P:\test>test Looking for fred : Looking for inetUser : top -> inetUser Looking for managedApplication : top -> application -> managedApplica +tion Looking for personnel : top -> person -> organizationalPerson -> managedPerson -> personne +l

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

Replies are listed 'Best First'.
Re^2: trees and depth-first search
by Excalibor (Pilgrim) on Oct 27, 2004 at 15:19 UTC

    Exactly like that, thank you! :-)

    PS: It's really elegant, I don't think I would have gotten it so cool (and now I see the 'proper' stack unwinding returning values... silly me... Thanks for the great leson!)

    --
    our $Perl6 is Fantastic;