For the general case, you'd need a recursive solution to traverse the pred lists. For this particular case, you don't have to worry about something being a pred-of-a-pred. I believe I have fixed the recursive section, as well.
my %hash=(
'MEX1J' => {
desc => 'Job 2' ,
pred => ['TEX1J'],
},
'MEX2J' => {
desc => 'Job end',
pred => ['TROUBLE'],
},
'TEX1J' => {
desc => 'Job start',
pred => [],
},
'TROUBLE' => {
desc => 'who cares',
pred => ['MEX1J']
}
);
sub pred_cmp {
my ($i1, $i2) = @_;
# Anybody with no preds is first
if (@{$hash{$i1}{pred}} == 0) {
return -1;
}
elsif (@{$hash{$i2}{pred}} == 0) {
return 1;
}
# If one is a pred of the other, it's first
elsif (grep {$_ eq $i2} @{$hash{$i1}{pred}}) {
return 1;
}
elsif (grep {$_ eq $i1} @{$hash{$i2}{pred}}) {
return -1;
}
else {
# Check recursively
my ($rec) = grep $_, map {pred_cmp($_, $i2)} @{$hash{$i1}{pred
+}};
if ($rec) { print "Returning $rec\n"; return $rec }
($rec) = grep $_, map {pred_cmp($i1, $_)} @{$hash{$i2}{pred}};
if ($rec) { print "Returning $rec\n"; return $rec }
return 0;
}
}
for (sort {pred_cmp($a,$b)} keys %hash) {
print "$_\n";
}
Caution: Contents may have been coded under pressure.
-
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.