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 } #### l c e n a d j k g h b f o i