Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: check if an element exists in array

by RecursionBane (Beadle)
on Apr 12, 2011 at 01:43 UTC ( [id://898818]=note: print w/replies, xml ) Need Help??


in reply to check if an element exists in array

For those getting here through the Google terms "element exists in array perl", here's a simple routine I wrote because I wanted something similar to TCL's "lsearch -exact" but with a binary return:
# Checks if a provided element exists in the provided list # Usage: isInList <needle element> <haystack list> # Returns: 0/1 sub isInList { my $needle = shift; my @haystack = @_; foreach $hay (@haystack) { if ( $needle eq $hay ) { return 1; } } return 0; }
Of course, this should only be used on small haystacks (a few hundred elements at most).

Replies are listed 'Best First'.
Re^2: check if an element exists in array
by jdporter (Paladin) on Apr 12, 2011 at 16:49 UTC
    sub isInList { my( $d, $it ) = ( "\0", @_ ); join( $d, '', @_, '' ) =~ /$d\Q$it\E$d/ }

    Caveat: This treats all the values as strings. Input values which are not strings will get stringified! This may or may not yield the desired results.

      Elegant! Does Perl automagically return the last modified variable when returning from a subroutine?

        "Last modified variable"? No, it returns the value of the last evaluated expression.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://898818]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-19 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found