0

So I have this Perl code:

$array->[0][0] = "cc";
$array->[0][1] = "3";
$array->[1][0] = "aaaa";
$array->[1][1] = "2";
$array->[2][0] = "bb";
$array->[2][1] = "1";

And I need it sorted in alphabetical order (second column) so that $array->[0][0] is "aaaa" and $array->[0][1] is "2"

I must have been asleep during Programming 101 in the 90's. I've spent hours trawling code and tutorials on the net and just can't get it. Can someone provide me with some sample code please. thanks!

0

2 Answers 2

9

Just sort the dereferenced array by the first element:

$array = [ sort { $a->[0] cmp $b->[0] } @$array ];

or

@$array = sort { $a->[0] cmp $b->[0] } @$array;

Returns:

[ [ 'aaaa', '2' ],
  [ 'bb',   '1' ],
  [ 'cc',   '3' ] ]
Sign up to request clarification or add additional context in comments.

1 Comment

that's awesome, thanks @choroba - I was using '<=>' instead of 'cmp'. works perfectly. thanks!
4

If you can reach into CPAN, use the sort_by function provided by List::UtilsBy (or via List::AllUtils)

use List::AllUtils 'sort_by';
$array = [ sort_by { $_->[0] } @$array ];

... or alternatively using Sort::Key

use Sort::Key 'keysort';
$array = [ keysort { $_->[0] } @$array ];

Both achieve the same thing, but you should really try to get a modern version of List::AllUtils as it will save you from reinventing a lot of wheels.

1 Comment

Or @$array = ... @$array; instead of $array = [ ... @$array ]; to avoid creating a new array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.