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:
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