How can I sort multiple arrays according to one array?

I have a data structure such as

@colors = qw(red blond green);
@numbers = qw(349 1234.5678 3.14159265);
@hats = qw(fedora porkpie bowler);
my %hash = (colors => \@colors, numbers => \@numbers, hats => \@hats);

I want to sort this according to the values ​​of one of the arrays, while maintaining the association of the elements of the parallel array. That is, if I exchange $hash{numbers}[2]and index $hash{numbers}[3], I want to do the same exchange for all other arrays in the hash. In this case, if I am sort {$a <=> $b}on numbers:

$sorted{numbers} = [3.14159265, 349, 1234.5678];
$sorted{colors}  = ["green", "red", "blond"];
$sorted{hats}  = ["bowler", "fedora", "porkpie"];

The decision, which I am using now inverts the structure of %hashthe array, where $array[$i]{$k} == $hash{$k}[$i], @sorted = sort {$a->{numbers} <=> $b->{numbers}} @arrayand then converts @sortedback to an array of hashes, hash arrays.

I don't care if the variety is stable, I'm just wondering if there is a better way to do this.

+3
1

, .

my @permutation = sort { $numbers[$a] <=> $numbers[$b] } (0..$#numbers);
@colors = @colors[@permutation];
@numbers = @numbers[@permutation];
@hats = @hats[@permutation];
# No change to %hash needed, since it has references to above arrays.
+10

Source: https://habr.com/ru/post/1771559/


All Articles