How do I custom sort a 2D array in perl? -
i have 2d array create this:
# in loop push @{ $list[$array_index++] }, ($x[0], $x[1], $x[2], $y);
i tried writing sort function array this:
@sorted = sort {$a->[3] > $b->[3]} @list;
but doesn't seem work.
what want sort "rows" based on value of "third column" of each "row". how do it?
you got it, you're using wrong operator. sort subroutine needs return 1 of 3 values. numeric comparison, can use spaceship (<=>
) returns -1 if left-hand argument less right, 0 if equal, or 1 if left-hand greater right.
so:
@sorted = sort {$a->[3] <=> $b->[3]} @list;
(note that's fourth column since arrays zero-indexed. i'm assuming that's want.)
Comments
Post a Comment