I’m looking for presence of an element in a list.
In Python there is an in keyword and I would do something like:
if element in list:
doTask
Is there something equivalent in Perl without having to manually iterate through the entire list?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
UPDATE:
If you can get away with requiring Perl v5.10, then you can use any of the following examples.
The smart match
~~operator.You could also use the
given/whenconstruct. Which uses the smart match functionality internally.You can also use a
forloop as a “topicalizer” ( meaning it sets$_).One thing that will come out in Perl 5.12 is the ability to use the post-fix version of
when. Which makes it even more likeifandunless.If you have to be able to run on older versions of Perl, there still are several options.
You might think you can get away with using List::Util::first, but there are some edge conditions that make it problematic.
In this example it is fairly obvious that we want to successfully match against
0. Unfortunately this code will printfailureevery time.You could check the return value of
firstfor defined-ness, but that will fail if we actually want a match againstundefto succeed.You can safely use
grephowever.This is safe because
grepgets called in a scalar context. Arrays return the number of elements when called in scalar context. So this will continue to work even if we try to match againstundef.You could use an enclosing
forloop. Just make sure you calllast, to exit out of the loop on a successful match. Otherwise you might end up running your code more than once.You could put the
forloop inside the condition of theifstatement …… but it might be more clear to put the
forloop before theifstatement.If you’re only matching against strings, you could also use a hash. This can speed up your program if
@listis large and, you are going to match against%hashseveral times. Especially if@arraydoesn’t change, because then you only have to load up%hashonce.You could also make your own subroutine. This is one of the cases where it is useful to use prototypes.