Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Answer: How to find out if X is an element in an array?

by Roger (Parson)
on Sep 10, 2003 at 03:21 UTC ( #290287=categorized answer: print w/replies, xml ) Need Help??

Q&A > arrays > How to find out if X is an element in an array? - Answer contributed by Roger

$X = "x"; @array = qw / x y z 1 2 3 /; return exists {map { $_ => 1 } @array}->{$X};
The above code returns 1 if element found, undef if not found.

Replies are listed 'Best First'.
Re: Answer: How to find out if X is an element in an array?
by NetWallah (Canon) on Sep 10, 2003 at 06:29 UTC
    Hmm - This method will not scale well because it creates a temporary hash. If this is a repeated search in a large array, you would be doing a lot of memory management.

    Here is the equivalent code, using grep:

    $X = "x"; @array = qw / x y z 1 2 3 /; return scalar grep(/^$X$/,@array) > 0;
    The "scalar" isnt really necessary, but it documents the fact that grep is called in a scalar context.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2020-10-19 21:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (206 votes). Check out past polls.

    Notices?