Dave's Brain

Browse - programming tips - perl is an element in an array

Date: 2008apr19
Language: perl

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, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.