cens has asked for the wisdom of the Perl Monks concerning the following question:

okay, I know this seems like a dumb question, but I can't think of a solution to the problem.

Scenario:

I have a hash where the key is a username and the value is a score(integer). I want to sort the hash by value, which I can do (a la the camel book). But after that, I want to find out if anyone has the same score, and return the keys of the tie socres. The problem is that I can't figure out how to look through the hash and return the key correctly. I am completely stumped.

I think that I would want to use something like:

@keys = sort{$hash{$a} cmp $hash{$b}} keys %hash;

and say

if ($hash{$a} cmp $hash{$b} = true) {return ($hash{$a} , $hash{$b})}

and stuff that stuff the result in the array. However, I can't get it to work. Any advice would be greatly appreciated, thanks in advance.

Replies are listed 'Best First'.
•Re: Comparing values in a hash
by merlyn (Sage) on Sep 05, 2002 at 23:11 UTC
    Do it by inverting the hash:
    my %revhash; while (my($k, $v) = each %hash) { push @{$revhash{$v}}, $k; } for my $val (sort { $a <=> $b } keys %revhash) { my @keys = @{$revhash{$_}}; if (@keys > 1) { # only items where there's a tie print "$val is shared by @keys\n"; } }

    -- Randal L. Schwartz, Perl hacker

      I presume you're doing the first each loop for clarity of exposition; can't you just do: my %revhash = reverse %hash;Or am I missing something?

      Thank you very much. I feel like an idiot...should have known that.