in reply to Top and bottom 10 percent elements of an array

It's simpler if you sort the indexes instead of the values.

my $portion = 0.20; my @array = (2, 4, 3, 8, 9, 12, 13, 20, 18, 7); my $keep = int(@array * $portion); my @sorted_idxs = sort { $array[$a] <=> $array[$b] } 0..$#array; my @final = ('-') x @array; $final[$sorted_idxs[$_]] = 'B' for 0..$keep-1; $final[$sorted_idxs[$_]] = 'A' for -$keep..-1; print("@final\n");
B - B - - - - A A -

Update: Fixed off-by-one error.