Ah, a topological sort. Which you can be reduced to sorting if there are no conflicting requirements. (Sometimes you can do a topological sort faster than an ordinary sort, but you never need more time than a regular sort).
I'd preprocess the 'pred' arrays so I can faster search in them, after that, I'd do a regular sort:
#!/usr/bin/perl
use strict;
use warnings;
my %hash = (
MEX1J => {
desc => 'Job 2',
pred => [qw /TEX1J/],
},
MEX2J => {
desc => 'Job End',
pred => [qw /TEX1J MEX1J/],
},
TEX1J => {
desc => 'Job start',
pred => [],
},
);
#
# Preprocess, transform the 'pred' arrays into hashes.
#
while (my ($key, $value) = each %hash) {
$value->{pred_h} = {map {($_, 1)} @{$value->{pred}}};
}
#
# Sort keys.
#
my @keys = sort {$hash{$b}{pred_h}{$a} ? -1 :
$hash{$a}{pred_h}{$b} ? 1 : 0} keys %hash;
#
# Print keys.
#
print "$_\n" for @keys;
__END__
TEX1J
MEX1J
MEX2J
Note that you can write the sort block as:
{$hash{$a}{pred_h}{$b} - $hash{$b}{pred_h}{$a}}
but that's rather obscure, and you'd need to turn off warnings.
-
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.