http://qs321.pair.com?node_id=1101632


in reply to sorting array of array references with multiple dereferenced array elements

If we knew in advance how many elements each of your sub-arrays were going to have, and if it were a fairly small number, we could do this with an inlined sort routine, perhaps something along these lines (assuming three elements in each sub-array):

use Data::Dumper; print Dumper(+{ unsorted => \@array }); @array = sort { $$a[0] <=> $$b[0] or $$a[1] <=> $$b[1] or $$a[2] <=> $$b[2] } @array; use Data::Dumper; print Dumper(+{ sorted_on_first_three_elements => \@array });

Note: This code is untested.

This is pretty basic, and works when we don't mind listing each of the sort criteria.

However, if we don't know how many elements there are, or if there are a whole bunch, it may be more practical to have the sort routine loop over the subarray indices from 0 to whatever, returning as soon as it has an answer. (The return values should match what <=> would return; see perlop for further information about that.)

use Data::Dumper; print Dumper(+{ unsorted => \@array }); @array = sort { for my $i (0 .. $#a) { if (not ($$a[$i] == $$b[$i])) { return $$a[$i] <=> $$b[$i]; } } return 0; } @array; use Data::Dumper; print Dumper(+{ sorted => \@array });

Note: This code is untested.

Note too that the way you define the AoA feels kind of awkward, like maybe you aren't really comfortable with Perl data structures yet. That's fine, at first, but you will want to work toward being more comfortable with Perl data structures until you are able to do things like this:

my @user = ( # [ username, fullname, authlevel, { otherinfo } ], [ 'george', 'George Jetson', $AUTH_EMPLOYEE, { supervisor => 'spaceley', pet => 'astro', } ], [ 'astro', 'Astro', $AUTH_BASIC, { supervisor => 'george', } ], [ 'hhoyt', 'Herman Hoyt', $AUTH_PROFESSOR, { supervisor => 'amcclain', department => 'theology', } + ], # and so on and so forth );