in reply to Build Sort dynamically
But if you're building the sort sub dynamically the simplest thing to do is to build an array of sort closures, then combine them into a sort sub. Re: Fun with complex sorting on arbitrary criteria list. can show you how to combine the closures into a single sort subroutine. (Note that there I don't use the ($$) prototype and here I do. That is a good habit because it is very useful to be able to set up the sort routine in one package and call it in the other. It doesn't work on Perl 5.005, but that is not widely used any more.) As for the individual sort subs, they might look something like this (all code is untested):
And then the actual sort would use a Schwartzian transform like this:my $field_index = $position{$field}; if ("text" eq $type{$field}) { if ("asc" eq $order{$field}) { push @sort_sub, sub ($$) { $_[0][0][$field_index] cmp $_[1][0][$field_index]; }; } else { push @sort_sub, sub ($$) { $_[1][0][$field_index] cmp $_[0][0][$field_index]; }; } } else { if ("asc" eq $order{$field}) { push @sort_sub, sub ($$) { $_[0][0][$field_index] <=> $_[1][0][$field_index]; }; } else { push @sort_sub, sub ($$) { $_[1][0][$field_index] <=> $_[0][0][$field_index]; }; } }
Update: I had a trailing comma after sort $sort_routine. Now fixed.my @sorted_list = map {$_[1]} sort $sort_routine map {[[split $_, "|"], $_]} @list;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Build Sort dynamically
by AnomalousMonk (Archbishop) on Aug 24, 2008 at 05:17 UTC | |
by tilly (Archbishop) on Aug 24, 2008 at 06:19 UTC | |
by AnomalousMonk (Archbishop) on Aug 24, 2008 at 07:33 UTC | |
by tilly (Archbishop) on Aug 24, 2008 at 07:47 UTC |