I'm not that smart, so I just played with L~R's code and I got it to produce one of the outcomes you said was expected.
There are lots of extra "prints" in there so I can see what's happening with the recursion ...
Code:
#!/usr/bin/perl
use strict;
use warnings;
my %tree = (
FOO => [qw/BAR BLAH ASDF/],
BAR => [qw/LA/],
BLAH => [qw/XYZ/],
ASDF => [qw/OOOOO/],
LA => [],
XYZ => [qw/LA/],
OOOOO => []
);
{
my %seen;
my %onstack;
my @list;
sub how_to_uninstall {
my $target = shift;
### COMMENT OUT THE FOLLOWING LINE ###
# (@list, %seen, %onstack) = ();
print "HOWTO ($target) START\n";
_traverse($target);
### NEW STUFF ###
for my $token (keys(%tree)) {
for (@{$tree{$token}}) {
if (defined($seen{$_}) != 1) {
how_to_uninstall($token);
}
}
}
### END NEW STUFF ###
print "HOWTO ($target) FINISH\n";
return @list;
}
sub _traverse {
my $x = shift;
print " TRAVERSE ($x) START\n";
$seen{$x} = $onstack{$x} = 1;
for my $y (@{$tree{$x}}) {
die "cyclic!" if $onstack{$y}; # back edge
print " Found $y\n";
_traverse($y) unless $seen{$y};
}
push @list, $x;
$onstack{$x} = 0;
print " TRAVERSE ($x) FINISH\n";
}
}
my @order = how_to_uninstall('BLAH');
print "\nANSWER = @order\n";
Test Run:
{C} > 808487.pl
HOWTO (BLAH) START
TRAVERSE (BLAH) START
Found XYZ
TRAVERSE (XYZ) START
Found LA
TRAVERSE (LA) START
TRAVERSE (LA) FINISH
TRAVERSE (XYZ) FINISH
TRAVERSE (BLAH) FINISH
HOWTO (ASDF) START
TRAVERSE (ASDF) START
Found OOOOO
TRAVERSE (OOOOO) START
TRAVERSE (OOOOO) FINISH
TRAVERSE (ASDF) FINISH
HOWTO (FOO) START
TRAVERSE (FOO) START
Found BAR
TRAVERSE (BAR) START
Found LA
TRAVERSE (BAR) FINISH
Found BLAH
Found ASDF
TRAVERSE (FOO) FINISH
HOWTO (FOO) FINISH
HOWTO (ASDF) FINISH
HOWTO (BLAH) FINISH
ANSWER = LA XYZ BLAH OOOOO ASDF BAR FOO
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|