Gossamer Forum
Home : General : Perl Programming :

Sorting 'mutlidimensional' array

Quote Reply
Sorting 'mutlidimensional' array
Any help on this one would be great!

I need to be able to sort an array of lists by specific columns.

For example, I need to sort @data by: $data[][$cols{FIRSTNAME}], $data[][$cols{LASTNAME}], $data[][$cols{ADDRESS}], etc where $cols is a hash pointing me to the correct column index in @data. Everything I have found with regards to sort is only on simple arrays....

Thanks for your help!
Quote Reply
Re: [Wetzerk] Sorting 'mutlidimensional' array In reply to
I'm not sure exactly how your data is laid out but see if this helps:

Code:
my @data = (
[ { FIRSTNAME => 'Someother',
LASTNAME => 'Name',
ADDRESS => '123 4nd St.'}
],
[ { FIRSTNAME => 'Charlie',
LASTNAME => 'Piper',
ADDRESS => '123 2nd St.'}
],
[ { FIRSTNAME => 'First',
LASTNAME => 'Name',
ADDRESS => '123 3nd St.'}
],
);

sub complex_arrays {
$a->[0]->{FIRSTNAME} cmp $b->[0]->{FIRSTNAME} ||
$a->[0]->{LASTNAME} cmp $b->[0]->{LASTNAME} ||
$a->[0]->{ADDRESS} cmp $b->[0]->{ADDRESS};
}

my @sorted = sort complex_arrays @data;

print 'Sorted:' . $/ . '-' x 20 . $/;
foreach (@sorted) {
print "$_->[0]->{FIRSTNAME} $_->[0]->{LASTNAME} lives at $_->[0]->{ADDRESS}$/";
}

Read up on sort, references and data structures::

http://www.perldoc.com/perl5.8.0/pod/perldsc.html
http://www.perldoc.com/perl5.8.0/pod/perlreftut.html
http://www.perldoc.com/perl5.8.0/pod/perlref.html

A little hairy at first but not nearly as bad as they look :)

~Charlie