http://qs321.pair.com?node_id=433194

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

I have many (sometimes more than 100) tasks to perform in perl. Some of these tasks are concerned with order (task a must complete before task c, for example). Others may not care about order (independant of other tasks). There are no loops (e.g., a may require c, but c may not require a, even indirectly). Note that there is more than one possible solution to this. I'm not concerned with "best" (I can't even define "best"). I'm merely concerned with coming up with a valid solution, one that, given the same input (same list of tasks, same requirements) gives the same list (the reason for this is a bit complex, so I won't get into that just now).

I'm trying to come up with a way to get sort to do this. Really, I'm not concerned with having to use sort, but I was thinking sort would be the easy way to do this. It doesn't seem to be. Here is a completely rewritten example of what I'm doing (the original code is thousands of lines long and proprietary).

use strict; use Data::Dumper; my %before = ( a => _s(qw(c)), b => _s(qw(d e)), c => _s(qw(l)), d => _s(qw(e a)), e => _s(qw(c)), f => _s(qw(g d)), g => _s(qw(c)), h => _s(qw(g i)), i => _s(qw()), j => _s(qw(c)), k => _s(qw()), l => _s(qw()), n => _s(qw(c)), o => _s(qw()), ); print Dumper(\%before); my @order = sort { #print "Checking $a vs $b\n"; prereq($a, $b) <=> prereq($b, $a) } keys %before; print "@order\n"; sub prereq { my ($l, $r) = @_; if (exists $before{$l}{$r}) { return 1; } if (grep { prereq($_, $r) } keys %{$before{$l}}) { return 1; } 0; } # setup - create a hash for easy access sub _s { my %h = map { $_ => 1 } @_; \%h }
The output is:
l c e n a d j k g h b f o i
I'm expecting that "h" should come after "i" (since h requires i). However, if I uncomment the print in the sort, I notice that h and i aren't even compared.

I originally noticed this problem on AIX using perl 5.8.0, and the above code was tested using Linux perl 5.8.5. For many reasons, perl 5.8 is a requirement (XML::Twig works better with 5.8 than 5.6).