Another way to think about it is: if you are having to look up values to find keys you have built your hash the wrong way aroung. Hashes are good looking up keys to find values but not so good for looking up values to find keys. So, when you create your hash, swap the keys and values. Then your lookup will be easy.

You can try something like the following:

#!/usr/bin/perl # use strict; use warnings; use Data::Dumper; my %hash1; my %hash2; foreach my $line (<DATA>) { my ($key, $value) = split(/\s+/, $line); push(@{$hash1{$key}}, $value); push(@{$hash2{$value}}, $key); } print Dumper(\%hash1); print Dumper(\%hash2); print "Values for key a are @{$hash1{a}}\n"; print "Keys with value b are @{$hash2{b}}\n"; print "Keys with value h are @{$hash2{h}}\n"; __DATA__ key value a b a c a d e f g h g i j h

Which produces

$VAR1 = { 'e' => [ 'f' ], 'a' => [ 'b', 'c', 'd' ], 'g' => [ 'h', 'i' ], 'j' => [ 'h' ], 'key' => [ 'value' ] }; $VAR1 = { 'c' => [ 'a' ], 'h' => [ 'g', 'j' ], 'b' => [ 'a' ], 'value' => [ 'key' ], 'd' => [ 'a' ], 'f' => [ 'e' ], 'i' => [ 'g' ] }; Values for key a are b c d Keys with value b are a Keys with value h are g j

In reply to Re: get a key for a value revisited by ig
in thread get a key for a value revisited by marc.garcia

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.