in reply to Sort by value - new twist

This is untested, but it seems like you should be able to do something like:

sub mysort { $_[0]->{$a} cmp $_[0]->{$b} } # ... later ... for my $key (sort mysort(\%hash), keys %hash) { # and so on
In other words, pass a reference to the hash to the sort function.

Replies are listed 'Best First'.
Re^2: Sort by value - new twist
by shemp (Deacon) on Sep 01, 2004 at 19:27 UTC
    This ends up with some weird behaviour. I'm not exactly sure whats happening, but i dont think the param \%hash is being passed to the sorter in a manner that we (I) think it is.

    Try this:

    my %hash = ( 1 => 'A', 2 => 'B', 3 => 'C', ); foreach my $key (sort mysort(\%hash), keys %hash) { print "$key\n"; } sub mysort { print "mysort: \$_[0] = $_[0] ::: a = $a ::: b = $b\n"; return $_[0]->{$a} cmp $_[0]->{$b}; }
    ...lots of warnings and unexpected things.