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

Hi Monks

I have a hash whose keys are unique but the values might be repeated. Like

%hash = (1 => 'One', 2 => 'Two', 3 => 'One');


I want to get the keys for which the value is same.
In the above sample, i want 1 and 3 as result.

Can anyone sugesst a solution for this.
Thanks in advance

Replies are listed 'Best First'.
Re: Getting the keys of identical values in a hash
by jdporter (Paladin) on Sep 14, 2005 at 13:59 UTC
    My first inclination is to use arrays, as Zaxo did above. But I think maybe hashes would be easier:
    my %ih; $ih{$hash{$_}}{$_}++ for keys %hash; print for grep { keys %{$ih{$_}} > 1 } keys %ih;
    I also think a while/each might be nice here, as it makes the inversion of the hash a bit clearer:
    while ( my($key,$val) = each %hash ) { $ih{$val}{$key}++; }

      Thanks a lot for all your suggestions.It worked fine

      Thanks

Re: Getting the keys of identical values in a hash
by Zaxo (Archbishop) on Sep 14, 2005 at 13:39 UTC

    Invert the hash, putting keys in anonymous arrays,

    my %hash = {1 => 'One', 2 => 'Two', 3 => 'One'}; my %ihash; push @{$ihash{$hash{$_}}}, $_ for keys %hash; print "@{$hash{One}}\n";

    After Compline,
    Zaxo

      And then check for keys whose anonymous array has more than one value:
      my @same_value_keys = grep { @{$_} > 1 } values %ihash;
      where each array element is itself an array of keys with the same value in the original hash.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Re: Getting the keys of identical values in a hash
by svenXY (Deacon) on Sep 14, 2005 at 13:46 UTC
    Tested working code:
    my %hash = (1 => 'One', 2 => 'Two', 3 => 'One'); # fixed: not {} my %seen; foreach my $key (keys %hash) { push @{$seen{$hash{$key}}}, $key; } foreach (keys %seen) { print "Keys having $_ as value: " . join(', ', @{$seen{$_}}) . "\n +" if @{$seen{$_}} > 1; }
    output:
    Keys having One as value: 1, 3
    svenXY
Re: Getting the keys of identical values in a hash
by chester (Hermit) on Sep 14, 2005 at 13:51 UTC
    Note that you're defining the hash incorrectly; you need () not {}. You're storing a hashref as the only key of %hash, with no values. This is a good reason to use warnings;; then you get something about expecting an even-sized list.