I am new to Perl and stuck with a (likely simple) array sorting problem.
I've inherited some Perl code that reads lines from a text file into three 1-D arrays (x,y,z). I'd like to be able sort these arrays using one of the dimensions as the key and reordering the other two dimensions to match.
For example, if my input is:
and I sort by x, I'd like the result to be:
I could merge the three 1-D arrays into a 2-D array if that makes life easier.
Merging all the arrays together isn't necessary. Use sort
to get the correct index ordering for the elements in @x
:
@sort_by_x = sort { $x[$a] <=> $x[$b] } 0 .. $#x; # ==> (0, 2, 1)
Then apply that index ordering to any other array:
@x = @x[@sort_by_x];
@y = @y[@sort_by_x];
@z = @z[@sort_by_x];
use strict;
use warnings;
use Data::Dumper;
use List::Util qw(reduce);
my @x = (1, 3, 2);
my @y = (11, 13, 12);
my @z = (21, 23, 22);
my @combined = map { [ $x[$_], $y[$_], $z[$_] ] } 0 .. $#x;
my @sorted = sort { $a->[0] <=> $b->[0] } @combined;
my $split_ref = reduce { push @{$a->[$_]}, $b->[$_] for 0 .. $#$a; $a;} [[], [], []], @sorted;
print Dumper \@combined;
print Dumper \@sorted;
print Dumper $split_ref;
Which will essentially give you:
[
[
1,
2,
3
],
[
11,
12,
13
],
[
21,
22,
23
]
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With