in reply to Re: Re: sorting hashes by value
in thread sorting hashes by value

No, that won't work. If you need to keep the values along with the keys you can build it into the sort:

@pairs = sort { $a->[1] <=> $b->[1] } map { [ $_ => $word_list{$_} ] } keys %word_list; print "word $_->[0] = $_->[1]\n" for @pairs;

This works by building up a list of two-element arrays using map. The first element is the key and the second element is the value. Then sort is used to sort them by the second element. The return value is a list of two-element arrays, sorted by their second element.

You might recognize this as the tail of a Schwartzian Transform.

-sam

Replies are listed 'Best First'.
Re: Re: Re: Re: sorting hashes by value
by waswas-fng (Curate) on Nov 08, 2002 at 21:44 UTC
    Or it may be easier to understand as this:
    foreach my $sortedkey (sort {$hashname{"$a"} <=> $hashname{"$b"} } key +s %hashname) { printf "Value: %d Key: %s", %hashname{"$sortedkey"}, $sortedkey; }


    -Waswas
Re: Re: Re: Re: sorting hashes by value
by imlou (Sexton) on Nov 08, 2002 at 21:58 UTC
    Thanks Sam. Now I getting a better understanding of how map and sort works!