use constant M => 9; use constant N => 9; my @index_sorted; for my $m (0..(M-1)) { my $ix0 = $m * N push @index_sorted, sort { $sim[$ix0 + $b] <=> $sim[$ix0 + $a] } 0..(N-1); }