Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Specify sort method on the fly

by eric256 (Parson)
on Jan 20, 2010 at 22:44 UTC ( #818579=note: print w/ replies, xml ) Need Help??


in reply to Specify sort method on the fly

If you use a hash to hold different sort functions, then you can call that function from inside the sort block. There are probably better ways to do this, but this works.

#!/usr/bin/perl use strict; use warnings; my $test = shift; my $sort = { 'numbers' => sub { $_[0] <=> $_[1] }, 'letters' => sub { "$_[0]" cmp "$_[1]" }, }; my @test = qw/1 2 3 4 a b 0 10 9 100/; print sort {$sort->{$test}->($a,$b)} @test;

If you run this perl sort_test.pl letters it will use the cmp and if you run perl sort_test.pl numbers it will sort using <=>


___________
Eric Hodges


Comment on Re: Specify sort method on the fly
Select or Download Code
Replies are listed 'Best First'.
Re^2: Specify sort method on the fly
by ikegami (Pope) on Jan 20, 2010 at 23:29 UTC
    my $sort = { };? my %sort = ( );!

      I tend to use references always, dunno why, habit i suppose. I like the way they look?


      ___________
      Eric Hodges

        I go for references too. Couple of justifications:

        Since I almost always want to pass by reference to avoid copying, and often want to pass in multiple arrays or hashes, having a reference is a good default.
        Not having non-reffed arrays and hashes floating around means more consistency in the use of $ and -> almost everywhere.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2015-07-28 02:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (251 votes), past polls