Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How to check whether my array contains element x

by vinoth.ree (Parson)
on Jan 17, 2013 at 13:04 UTC ( #1013773=note: print w/ replies, xml ) Need Help??


in reply to How to check whether my array contains element x

check if an element exists in array

Update:

I used one of my project this way!

if ( grep( /^$value$/, @array ) ) { print "found it"; }
Similar to if ( "value" ~~ @array ) but seems more explicit.


Comment on Re: How to check whether my array contains element x
Download Code
Re^2: How to check whether my array contains element x
by tobyink (Abbot) on Jan 17, 2013 at 13:24 UTC

    Works nicely until $value = "http+listener+1".

    Make sure you \Q...\E or quotemeta your value.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      ++ tobyink

      Thanks for the info!

Re^2: How to check whether my array contains element x
by MidLifeXis (Prior) on Jan 17, 2013 at 13:33 UTC

    You might want to change /^$value$/ to /^\Q$value\E$/, especially if $value may contain re metacharacters, but it depends on the application.

    while (<>) { chomp; print qr(^$_$), "\t", qr(^\Q$_\E$), "\n"; } __END__ foo (?-xism:^foo$) (?-xism:^foo$) foo[bar] (?-xism:^foo[bar]$) (?-xism:^foo\[bar\]$)

    --MidLifeXis

Re^2: How to check whether my array contains element x
by Your Mother (Canon) on Jan 17, 2013 at 20:26 UTC

    What they already said except that since you're not actually using regex, you shouldn't use regex. This will be faster and have fewer caveats (I inverted the statement as a matter of stylistic preference, not because it's necessary)–

    print "Found it.\n" if grep { $_ eq $value } @array;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (14)
As of 2014-11-27 16:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (186 votes), past polls