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

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;


Comment on Re: Comparing spaceships (cmp and <=> as options)
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2014-09-30 15:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (376 votes), past polls