As always, ikegami provides a clear (and clearly explained), effective solution.

Here's another approach that has the advantage of a bit more concision (I doubt it will actually run any faster), but the drawback that it uses some Perl idioms that may be unfamiliar to the programmer/maintainer. You can leave out the  defined test if you're absolutely sure a 'gene' will never be anything that looks false to Perl. (A similar problem, unaddressed, exists for the taxons.)

>perl -wMstrict -le "use List::Util qw(first); my %gg = ( 1567 => [ qw(NP_011 NP_012 NP_013 NP_025) ], 2000 => [ qw(NP_020 NP_021 NP_024 NP_025 NP_035) ], 9999 => [ qw(NP_900 NP_910 NP_902 0) ], 9998 => [], ); SEARCH: for my $gene_to_find (qw(NP_011 NP_025 NP_999 0)) { print qq{searching for gene '$gene_to_find':}; my $matching_taxon = first { defined first { $_ eq $gene_to_find } @{ $gg{$_} } } keys %gg ; my @all_matching_taxons = grep { defined first { $_ eq $gene_to_find } @{ $gg{$_} } } keys %gg ; print qq{ NOT found} and next SEARCH if not $matching_taxon; print qq{ first found: '$matching_taxon'}; my $all_found = join q{' '}, @all_matching_taxons; print qq{ all found: '$all_found'}; } " searching for gene 'NP_011': first found: '1567' all found: '1567' searching for gene 'NP_025': first found: '2000' all found: '2000' '1567' searching for gene 'NP_999': NOT found searching for gene '0': first found: '9999' all found: '9999'

See List::Util.


In reply to Re^2: how to access hash key from the hash value when hash key is pointing to an array of hash values? by AnomalousMonk
in thread how to access hash key from the hash value when hash key is pointing to an array of hash values? by BhariD

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.