http://qs321.pair.com?node_id=660800

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

Replies are listed 'Best First'.
Re: sorting a hash by value with ties
by ikegami (Patriarch) 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;