for my $a (0..@a) { for my $b (0..@b) { for my $c (0..@c) { for my $d (0..@d) { for my $e (0..@e) { # Build a hash with the permutation as the key, and the # number of zeros as the value $permutation{$a[$a].$b[$b].$c[$c].$d[$d].$e[$e]} = !$a + !$b + !$c + !$d + !$e; }}}}} # Now sort according to the number of zeros return sort {$permutation{$a} <=> $permutation{$b}} keys %permutation; #### return sort {$permutation{$a} <=> $permutation{$b} || $a cmp $b} keys %permutation;