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).
-
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.