Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Custom Sort An AoA

by kcott (Archbishop)
on Apr 02, 2014 at 04:01 UTC ( [id://1080675]=note: print w/replies, xml ) Need Help??


in reply to Custom Sort An AoA

G'day Limbic~Region,

This is a general solution which appears to tick all the boxes:

@list = sort { @$a <=> @$b || do { my $cmp; ($cmp = $a->[-$_] cmp $b->[-$_]) ? last : next for 1 .. @$a; $cmp; } } @list;

Here's my test:

Update: I wrote that this was "a general solution"; however, having reviewed some of your comments in this thread, I see what I've provided wasn't what you meant.

I've converted the code I originally posted, into what I suspect is closer to what you want; but, if it's not, please provide more details about what you're looking for.

#!/usr/bin/env perl use strict; use warnings; use Scalar::Util qw{looks_like_number}; my @master_alpha_list = ( ['blah', 'asdf', 'foo', 'bar'], ['two'], ['zzz', 'def', 'ghi'], ['one'], ['mmm', 'def', 'ghi'], ['qqq', 'xyz', 'aaa'] ); my @master_num_list = ( [ 0, 1, 2, 3 ], [ 2 ], [ 9, 3, 6 ], [ 1 ], [ 5, 3, 6 ], [ 7, 8, 1 ], ); my @alpha_asc = sort { @$a <=> @$b || gen_sort() } @master_alpha_list; my @alpha_dsc = sort { @$a <=> @$b || gen_sort(1) } @master_alpha_list +; my @num_asc = sort { @$a <=> @$b || gen_sort() } @master_num_list; my @num_dsc = sort { @$a <=> @$b || gen_sort(1) } @master_num_list; use Data::Dump; dd $_ for (\@alpha_asc, \@alpha_dsc, \@num_asc, \@num_dsc); sub gen_sort { my ($desc) = @_; my $compare = looks_like_number($a->[0]) ? \&cmp_num : \&cmp_alpha +; my ($x, $y) = $desc ? ($b, $a) : ($a, $b); my $cmp; ($cmp = $compare->($x->[-$_], $y->[-$_])) ? last : next for 1 .. @ +$a; return $cmp; } sub cmp_alpha { $_[0] cmp $_[1] } sub cmp_num { $_[0] <=> $_[1] }

Output:

[ ["one"], ["two"], ["qqq", "xyz", "aaa"], ["mmm", "def", "ghi"], ["zzz", "def", "ghi"], ["blah", "asdf", "foo", "bar"], ] [ ["two"], ["one"], ["zzz", "def", "ghi"], ["mmm", "def", "ghi"], ["qqq", "xyz", "aaa"], ["blah", "asdf", "foo", "bar"], ] [[1], [2], [7, 8, 1], [5, 3, 6], [9, 3, 6], [0 .. 3]] [[2], [1], [9, 3, 6], [5, 3, 6], [7, 8, 1], [0 .. 3]]

-- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1080675]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 04:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found