A-Kay
A-Kay

Reputation: 69

Perl sorting arrayref

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!

Upvotes: 0

Views: 958

Answers (2)

choroba
choroba

Reputation: 241928

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' ] ]

Upvotes: 9

elcaro
elcaro

Reputation: 2317

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.

Upvotes: 4

Related Questions