Reputation: 1005
I have a 2-dimensional array in Perl. I want to sort the columns in the array but I want to ignore the leftmost n columns. I want to sort by the values in row 0.
Let me clarify what might be a confusing description. I have a table like this:
Z W D F E C
0 1 2 3 4 5
6 7 8 9 0 1
I want to ignore some number of columns on the left, say the first two. I want to sort the remaining columns by the value in the first row. The end result is this:
Z W C D E F
0 1 5 2 4 3
6 7 1 8 0 9
How would I do that in an elegant way? I understand how to use comparison functions to do the sort but I don't see how to tell Perl to ignore the first n columns.
Upvotes: 0
Views: 197
Reputation: 35208
You need to create a relationship between the old order and the new order.
The following creates an array of indexes @new_order
which can be used to sort each row:
#!/usr/bin/perl
use strict;
use warnings;
my @data = map { [split] } <DATA>;
my @old_header = @{ $data[0] };
my %old_order = map { $old_header[$_] => $_ } ( 0 .. $#old_header );
my @new_header = ( splice( @old_header, 0, 2 ), sort @old_header );
my @new_order = @old_order{@new_header};
# Output Transformed Data
for (@data) {
print "@{$_}[@new_order]\n"
}
__DATA__
Z W D F E C
0 1 2 3 4 5
6 7 8 9 0 1
Outputs:
Z W C D E F
0 1 5 2 4 3
6 7 1 8 0 9
Upvotes: 1