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

Thanks! so when its sorted into @words does it keep the word and the value? So in order for me to print it do I
for $i (0.. $#words_list){ for $words (keys %{$words[$i]}){ print "word $i = $words\n"; } }
??

Replies are listed 'Best First'.
Re: Re: Re: sorting hashes by value
by samtregar (Abbot) on Nov 08, 2002 at 21:36 UTC
    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

      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
      Thanks Sam. Now I getting a better understanding of how map and sort works!
Re: Re: Re: sorting hashes by value
by Orsmo (Beadle) on Nov 08, 2002 at 22:55 UTC
    While samtregar is right in his method for keeping the keys and values together, you probably don't need to go to that trouble. Why not just do something like this:
    @words = sort { $word_list{$a} <=> $word_list{$b} } keys %word_list; foreach $word (@words) { print "word $word = $word_list{$word}\n"; }
    @words is already a sorted list of the keys in %word_list. Of course, this assumes that nobody is doing pesky things like adding to %word_list between the time you sorted it and the time you decided to print it.