in reply to Custom, Reusable Sort Subroutine for Hashes?

Personally, I would create an anonymous subroutine that knows the correct hash to use. I think the fancy term would be "currying":

my @list = (qw( a b c d e f )); sub by_score { my( $score ) = @_; return sub($$) { my( $a,$b ) = @_; warn "$a / $b"; $score->{$a} <=> $score->{$b} } } my $by = by_score({ a => 5, b => 4, c => 3, d => 6, e => -1 }); print join ",", sort( {$by->($a,$b)} @list ); $by = by_score({ a => -5, b => 4, c => -3, d => 6, e => -1 }); print join ",", sort( {$by->($a,$b)} @list );

I'm a bit unhappy with the (lack of) syntax that prevents me from inlining $by. I would have liked to write something like:

$by = by_score({ a => -5, b => 4, c => -3, d => 6, e => -1 }); print join ",", sort( $by, @list );

... but that's nothing that Perl likes, as Perl doesn't know whether $by should be part of @list or not.

Replies are listed 'Best First'.
Re^2: Custom, Reusable Sort Subroutine for Hashes?
by QM (Parson) on Aug 30, 2017 at 13:08 UTC
    Yes, very helpful.

    I was anticipating a sub generator of some sort, where the hash and comparison function are passed in, and a new anonymous sub is returned. This sub could then be used in the code block position of the sort command.

    Perhaps something like this, which steals some ideas from Choroba's post, though I've not tried it:

    sub make_sort_sub { my $coderef = shift; my $hashref = shift; my $sort_sub = sub { something goes here } return $sort_sub; } my %hash = ( a => 5, b => 4, c => 3 ); my $keys_by_value = make_sort_sub( { $hashref->{$a} <=> $hashref->{$b} }, \%hash); my @keys_sorted_by_value = sort $keys_by_value %hash;

    Then $keys_by_value can be reused elsewhere on the same hash. But can't be used on a different hash. :(

    Hmmm, I'm thinking there's not a really elegant solution.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of