Say, I have a list:
@abc = (5,7,6,2,7,1);
I have to obtain a sorted list as well as a sorted list index. So the output will be:
If you want to sort the indexes, you'll need to generate them
0..$#unsorted
Then you sort them like anything else
my @sorted_indexes = sort { $unsorted[$b] <=> $unsorted[$a] } 0..$#unsorted;
Grabbing the sorted values can be done using a slice.
my @sorted_values = @unsorted[ @sorted_indexes ];
This is my solution:
use strict;
use warnings;
my @abc = (5,7,6,2,7,1);
my $i = 0;
#Create an array of hashes (with value and index)
my @temp_abc = map { {value=>$_, index=>$i++} } @abc;
#Sort by the value of each hash
my @sorted_temp_abc = sort { $b->{value} <=> $a->{value} } @temp_abc;
#extract the values to array @sorted_list
my @sorted_list = map { $_->{value} } @sorted_temp_abc;
#extract the values to array @sorted_list_index
my @sorted_list_index = map { $_->{index} } @sorted_temp_abc;
print "@sorted_list\n"; #<-- prints: 7 7 6 5 2 1
print "@sorted_list_index\n"; #<-- prints: 1 4 2 0 3 5