in reply to Scoping issue when sorting with subroutines

OK,

So I can pass the hash or whatever to my routine:

print join "\n", sort up(\%nos) } keys %nos;
which is cool. Unfortunately, in stripping down my code to present it to the Monks, I actually stripped out the main source of my problem (doh).

The reason I want to use a sort subroutine is that I don't know how I want to sort the thing until runtime. So I want to call my routine like this:

foreach my $id (sort $by_sort_method keys %contents) {
And I'd like to pass the %contents hash to the subroutine.

How do I do that?

Replies are listed 'Best First'.
Re: Re: Scoping issue when sorting with subroutines
by mdillon (Priest) on Apr 12, 2002 at 17:50 UTC
    Use something like this to create $by_sort_method:
    sub create_sorter { my $contents = shift; return sub { # sort however you want here $contents{$a}{FOO} cmp $contents{$b}{FOO} }; } my $by_sort_method = create_sorter \%contents; foreach my $id (sort $by_sort_method keys %contents) { ... }