Dave's Brain

Browse - Programming Tips - How do I check if a string is in a perl array?

Date: 2008apr19
Language: perl

Keywords: member

Q.  How do I check if a string is in a perl array?

A.  Using the builtin grep function is efficient.

sub contains($@) { my($target, @list) = @_; $target = quotemeta($target); return grep(/^$target$/, @list) > 0; } # Example use: sub main() { my(@list) = qw(aaa bbb ccc); if (contains('bbb', @list)) { print "bbb is in the list\n"; } else { print "bbb is NOT in the list\n"; } if (contains('eee', @list)) { print "eee is in the list\n"; } else { print "eee is NOT in the list\n"; } } main();

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.