Reputation: 91
Say I have a 2D array in perl
[2, 4, 6, 1, 3, 2] # $i = 0
[5, 2, 4, 2, 1] # $i = 1
[8, 2, 3, 5, 7, 1, 3, 5] # $i = 2
[2, 1] # $i = 3
How can I sort one row so they remain in the same order?
such as:
[2, 4, 6, 1, 3, 2]
[1, 2, 2, 4, 5] # sorted row
[8, 2, 3, 5, 7, 1, 3, 5]
[2, 1]
I tried an easy route to sort the $i row,
@array[$i] = sort(@array[$i]);
It does nothing to change the order of the array, my other attempts have deleted the array row all together.
Other 2D sorting questions I can find are for reordering rows/sorting columns.
I'm sure the answer is very easy.
Upvotes: 0
Views: 367
Reputation: 53488
OK, the thing you need to know is - that an array of arrays in perl, is implemented as an array of array references.
So - $array[$i]
- is a reference to an array.
So you can simply:
@{$array[$i]} = sort @{$array[$i]};
Although note by default, sort does alphanumeric, rather than just numeric.
So you might want:
@{$array[$i]} = sort { $a <=> $b } @{$array[$i]};
Or if you want to do the whole lot:
@$_ = sort {$a<=>$b} @$_ for @array;
Upvotes: 6