Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

sorting a hash by value with ties

by craigt (Initiate)
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
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) +;

    Punitha

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (14)
As of 2014-10-23 15:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (125 votes), past polls