http://www.perlmonks.org?node_id=1047697


in reply to How to I check if a value is present in an array?

This seems rather similar to how to refer the index of an array to another array of the same length you asked a little over an hour ago, which already has several replies.

This one is a bit different, though, so here's what I would suggest. Since you will be looping over @gl for every item in @genes, put @gl in a hash (only the keys matter). You can use a hash slice:

    my %gl; @gl{@gl} = undef;

Then, the lookup is both simple and efficient:

    say for grep { exists $gl{$_} } @genes;

Complete example:

#!/usr/bin/env perl use 5.012; use warnings FATAL => 'all'; my @genes = (qw<one two three four>); my @gl = (qw< two three five six>); my %gl; @gl{@gl} = undef; # Efficient lookups say for grep { exists $gl{$_} } @genes;

Output:

two three