Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Comparing spaceships (cmp and <=> as options)

by moritz (Cardinal)
on May 20, 2013 at 15:41 UTC ( #1034353=note: print w/replies, xml ) Need Help??

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

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;

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2016-10-26 01:10 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (330 votes). Check out past polls.