Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by mascip (Pilgrim)
on May 22, 2013 at 12:06 UTC ( [id://1034726]=note: print w/replies, xml ) Need Help??


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

This blog post discusses the best answers to this question.

As a short summary, if you can install CPAN modules then the best solutions are:

if any(@ingredients) eq 'flour';
or
if @ingredients->contains('flour');
However, a more usual idiom is:
if any { $_ eq 'flour' } @ingredients
which i find less clear.

But please don't use the first() function! It doesn't express the intent of your code at all. Don't use the "Smart match" operator: it is broken. And don't use grep() nor the solution with a hash: they iterate through the whole list. While any() will stop as soon as it finds your value.
Check out the blog post for more details.

PS: i'm answering for people who will have the same question in the future.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-19 02:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found