in reply to Sorting by the hash value

This is probably what you want to do:

foreach my $key ( map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, $list{$_}] } keys %list ) { ...

See the Schwartzian Transform for more info.

Update: ok.. so I probably must have added the <joke> tags around ;) I figured it would be obvious... since the guy already has a subroutine to sort in. :).


He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

Chady | http://chady.net/

Replies are listed 'Best First'.
Re:x2 Sorting by the hash value
by grinder (Bishop) on Jul 29, 2002 at 06:45 UTC
    Wow! Using a Schwartz Transform to sort a hash by value is like using a sledgehammer to crack open a peanut. The ST is not cheap, it only wins when the cost of computing the key is relatively expensive, and accessing a hash value by key is one of the cheaper things you can do in Perl. I wonder just how much slower this is?

    # /usr/bin/perl -w use strict; use Benchmark qw/cmpthese/; cmpthese( shift || 10_000, { 'sort' => sub { sort keys %ENV }, 'sort by key' => sub { sort {$ENV{$a} cmp $ENV{$b}} keys %ENV }, 'sort by ST' => sub { map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, $ENV{$_}] } keys %ENV }, }); __END__ % perl -w sortem 100000 Benchmark: timing 100000 iterations of sort, sort by ST, sort by key.. +. sort: 2 wallclock secs ( 1.35 usr + 0.00 sys = 1.35 CPU) @ 73 +964.50/s (n=100000) sort by ST: 18 wallclock secs (17.72 usr + 0.00 sys = 17.72 CPU) @ 56 +44.62/s (n=100000) sort by key: 2 wallclock secs ( 1.34 usr + 0.00 sys = 1.34 CPU) @ 7 +4515.65/s (n=100000) Rate sort by ST sort sort by key sort by ST 5645/s -- -92% -92% sort 73964/s 1210% -- -1% sort by key 74516/s 1220% 1% --

    Yep, pretty slow! (I threw the straight sort in there as well, just to give an idea of the overhead incurred by using a sort code block).


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
      Wow! Using a Schwartz Transform to sort a hash by value is like using a sledgehammer to crack open a peanut.

      This realization ought to have been the clue that guided you to the true purpose of Chady's node. :)