Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

sorting a hash by value with ties

by craigt (Novice)
on Jan 07, 2008 at 11:28 UTC ( #660800=perlquestion: print w/ replies, xml ) Need Help??
craigt has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm sorting a hash by value. My problem is the order within the sort where there are value ties. I would like those keys with tie values to be sorted alphabetically within the sort order. Thanks in advance for any help. craigt

Comment on sorting a hash by value with ties
Replies are listed 'Best First'.
Re: sorting a hash by value with ties
by ikegami (Pope) on Jan 07, 2008 at 11:31 UTC
    Well, you can't sort a hash. Presumably you are sorting the keys of the hash?
    my @ordered_keys = sort { $hash{$a} cmp $hash{$b} # by value, then || $a cmp $b # by key } keys %hash; foreach my $key (@ordered_keys) { print("$key: $hash{$key}\n"); }
Re: sorting a hash by value with ties
by Punitha (Priest) on Jan 07, 2008 at 13:05 UTC

    Hi craigt

    Try this

    print "$_:$hash{$_}\n" for (sort {$hash{$a} cmp $hash{$b}} keys %hash) +;


Re: sorting a hash by value with ties
by Anonymous Monk on Jan 07, 2008 at 13:33 UTC
    I may be completely misunderstanding the OP's question, but it seems to me it may be related to the sorting of tied hash values.

    If so, sorting only the tied values of a hash might be something like this (UNTESTED):

    my @sorted_tied_values = sort { $a cmp $b } grep { tied $_ } values %hash;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://660800]
Approved by marto
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (13)
As of 2015-11-30 14:14 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (771 votes), past polls