One problem is that if you write
\sub {<=>}
, the
<=> doesn't receive any arguments (and doesn't even parse the way you want it to, because the parser expects a term, but finds an operator instead). So you have to write something like
sub { $_[0] <=> $_[1] }
instead. This code seems to work:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my $sort = 'hours'; # really comes from a switch
my %map = ( # sorting map
hours => [0, sub {$_[0] <=> $_[1]}],
code => [1, sub {$_[0] cmp $_[1]}],
name => [2, sub {$_[0] cmp $_[1]}],
);
# example data
my @records = (
[10, 'xyz232', 'secret project'],
[ 5, 'foo123', 'world domination'],
[ 7, 'bar666', 'have a beer'],
);
my $elem = $map{$sort}[0];
my $sorter = $map{$sort}[1];
my @sorted = sort { $sorter->($a->[$elem], $b->[$elem]) } @records;
say join "\t", @$_ for @sorted;