Andrew Gaffney wrote: > > In a program I'm working on, I build a hash "tree" of sorts that contains > package dependencies. Each key contains an array with the first level > dependencies of the key. Each one of those dependencies have their own key with > their first level dependencies in the hash. For example: > > my %tree = { package1 => [ package2, package3, package4 ], > package2 => [ package7 ], > package3 => [ package5 ], > package4 => [ package7, package6], > package5 => [ ], > package6 => [ ], > package7 => [ ] }; > > Now, I want to walk the tree starting with a known "package1" and build an > ordered list of packages to install. For example: > > package7 > package2 > package5 > package3 > (no package7 here because it is already in the list) > package6 > package4 > package1 > > I also want to be able to track what package is a dependency of what (which key > a certain value is under) with my tree structure. What is the easiest way to do > this? Is there a better way to do this?
Hi Andrew. Forgive the lack of explanation, I liked the challenge of this one and threw this together just before going to bed. I'll pick up any questions tomorrow. Just one thing, this will loop indefinitely if the dependencies are cyclic. Something like my %tree = ( package1 => [ qw/package2/ ], package2 => [ qw/package1/ ], ); But it's not hard to code for this case. Also, I'm not sure exactly how you want to 'track what package is a dependency of what'. If you just want a list of all packages that are dependent on a given package then that's fairly easy, but it should be done as a separate piece of code. HTH, Rob use strict; use warnings; use Data::Dumper; my %tree = ( package1 => [ qw/package2 package3 package4/ ], package2 => [ qw/package7/ ], package3 => [ qw/package5/ ], package4 => [ qw/package7 package6/ ], package5 => [ ], package6 => [ ], package7 => [ ] , ); my %remainder; my @install; @remainder{keys %tree} = (); while (keys %remainder ) { foreach my $package (keys %remainder) { my %dependencies; @[EMAIL PROTECTED] = (); delete @[EMAIL PROTECTED]; if (keys %dependencies == 0) { push @install, $package; delete $remainder{$package}; } } } print map "$_\n", @install; **OUTPUT package5 package6 package7 package2 package3 package4 package1 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>