Consuelo
Consuelo

Reputation: 23

How do I custom sort a 2D array in perl?

I have a 2D array which I create like this:

# i do this in a loop
push @{ $list[$array_index++] }, ($x[0], $x[1], $x[2], $y);

I tried writing the sort function for this array like this:

@sorted = sort {$a->[3] > $b->[3]} @list;

but it doesn't seem to work.

What I want to do is to sort the "rows" based on the value of the "third column" of each "row". How do I do it?

Upvotes: 2

Views: 633

Answers (1)

friedo
friedo

Reputation: 66978

You almost got it, but you're using the wrong operator. A sort subroutine needs to return one of three values. For a numeric comparison, you can use the spaceship (<=>) which returns -1 if the left-hand argument is less than the right, 0 if they are equal, or 1 if the left-hand is greater than the right.

So:

@sorted = sort {$a->[3] <=> $b->[3]} @list;

(Note that that's actually the fourth column since arrays are zero-indexed. I'm assuming that's what you want.)

Upvotes: 2

Related Questions