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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Specify sort method on the fly
by ikegami (Patriarch) on Jan 20, 2010 at 23:29 UTC | |
by eric256 (Parson) on Jan 21, 2010 at 15:05 UTC | |
by SuicideJunkie (Vicar) on Jan 21, 2010 at 16:32 UTC |
In Section
Seekers of Perl Wisdom