Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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

by rjt (Deacon)
on Aug 03, 2013 at 11:19 UTC ( #1047697=note: print w/replies, xml ) Need Help??

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;


two three

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1047697]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2018-06-22 13:40 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.