Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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?

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 lurking in the Monastery: (4)
As of 2016-02-12 02:36 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (387 votes), past polls