Gossamer Forum
Home : General : Perl Programming :

Ordering an array of arrays by one of the columns

Quote Reply
Ordering an array of arrays by one of the columns
I can handle arrays and the sort function. I have an array of arrays (it's really an array of multi-field records) Is there a mechanism to sort this AOA by reference to one of the columns only?
Douglas Maughan
Winchester, UK
Quote Reply
Re: [silvermist] Ordering an array of arrays by one of the columns In reply to
Do you mean an array of arrayrefs or an arrayref of arrayrefs?...AFAIK it is not possible to have an array of arrays as that would just be the same as one big array.

Last edited by:

Paul: Jan 19, 2003, 9:00 AM
Quote Reply
Re: [silvermist] Ordering an array of arrays by one of the columns In reply to
It sounds like you have an array of hashrefs (or possible arrayrefs). In the first case (array of hashrefs) you would sort as follows (@array is your array):
Code:
my @sorted_array = sort {$a->{key} <=> $b->{key}} @array;
where you need to replace 'key' by the hash key you are sorting on. Interchange $a and $b if you want to sort descending, interchange '<=>' with 'cmp' if you are sorting alphabetically.
For an array of arrayrefs you would do:
Code:
my @sorted_array = sort {$a->[1] <=> $b->[1]} @array;
where you need to replace 1 with the number of the field in the arrayref you want to sort on.

Ivan
-----
Iyengar Yoga Resources / GT Plugins
Quote Reply
Re: [silvermist] Ordering an array of arrays by one of the columns In reply to
See Declaration and Access of Arrays of Arrays at the PerlDoc site. ;)