http://www.perlmonks.org?node_id=1034383


in reply to Comparing spaceships (cmp and <=> as options)

Here is a version that uses a variant of the Schwartzian Transform.
my @records = ( [10, 'xyz232', 'secret project'], [ 5, 'foo123', 'world domination'], [ 7, 'bar666', 'have a beer'], ); my %sort_this_way = ( 'hours' => [0, sub { return sort { $a->[0][$a->[1]] <=> $b->[0][$b->[1]]; } @_; }], 'code' => [1, sub { return sort { $a->[0][$a->[1]] cmp $b->[0][$b->[1]]; } @_; }], 'name' => [2, sub { return sort { $a->[0][$a->[1]] cmp $b->[0][$b->[1]]; } @_; }], ); my $sort = 'hours'; # really comes from a switch my @new = map { $_->[0] } $sort_this_way{$sort}->[1]( map { [ $_ , $sort_this_way{$sort}->[0], $_->[ $sort_this_way{$sort}->[0] ] ] } @records );
Granted the sort part of the transform is actually a function call but I couldn't remember how to set up a function to not require parenthesis without defining a prototype first.


PJ
use strict; use warnings; use diagnostics;