infinitloop
infinitloop

Reputation: 3011

how to get a key based on a value using hashes in Perl?

how do i get a KEY based on a VALUE in Perl using hashes? if i have:

"dime"=>"4"
"nickle"=>"5"
"quarter"=>"2"
"dollar"=>"6"

now I sort them and highest is 6. I wanna be able to grab "dollar". Here is what i tried:

# sort money based on count
my @sorted = sort {$deposit->{$b} cmp $deposit->{$a}} keys %$deposit;
  my %rhash;
  @rhash{values %deposit} = keys %deposit;

  $owner = $rhash->{$sorted[0]}; #get highest count

Upvotes: 0

Views: 974

Answers (2)

tadmc
tadmc

Reputation: 3734

Sorting is O(n log n) which is more work than is needed. Finding the highest can be done with an O(n) algorithm. Here is an examply using the "high water mark" algorithm:

#!/usr/bin/perl
use warnings;
use strict;

my %deposit = (
    "dime"=>"4",
    "nickle"=>"5",
    "quarter"=>"2",
    "dollar"=>"6",
);

my $hi_key;
foreach (keys %deposit) {
    $hi_key = $_ if $deposit{$_} > $deposit{$hi_key};
}

print "high is: $hi_key => $deposit{$hi_key}\n";

Upvotes: 2

Alnitak
Alnitak

Reputation: 339786

If your values are unique, you can reverse the map thus:

my %rev = map { $deposit->{$_} => $_ } keys %$deposit;

[assuming that $deposit is a reference to the hash listed]

Upvotes: 3

Related Questions