in reply to Advanced Sorting

You could try something like this, though I'm not sure it's not uglier than what you have. :) Although this doesn't have a conditional in the sort-block, so it should be faster, I think.
my $field = "name"; sub numsort { $a->{$field} <=> $b->{$field} } sub alphasort { $a->{$field} cmp $b->{$field} } my @data = ( { name => 'jim', age => 16 }, { name => 'bob', age => 18 }, ); my $sortsub = $field eq "name" ? 'alphasort' : 'numsort'; my @sorted; { no strict 'refs'; @sorted = sort $sortsub @data; }
You need the "no strict 'refs'" because that
sort $sortsub @data
is actually using symbolic references, which is ugliness itself. :)

Can sort subs be sub references? From the docs I looked at, it doesn't seem like they can. If they could, that would be a *much* cleaner way of doing it.

Replies are listed 'Best First'.
RE: Re: Advanced Sorting
by chromatic (Archbishop) on Apr 20, 2000 at 02:53 UTC
    They sure can:
    #!/usr/bin/perl -w use strict; my @data = ( { name => 'jim', age => 16 }, { name => 'bob', age => 18 }, ); sub sort_me { my $field = shift; if ($field eq "name") { return sub { $a->{$field} cmp $b->{$field} }; } else { return sub { $a->{$field} <=> $b->{$field} }; } } my @sorted; my $type = sort_me("name"); @sorted = sort $type @data; $type = sort_me("age"); @sorted = sort $type @data;
    Closures are so nice.