>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'