[Israel.pm] checking for presence of a value in a list

Amir E. Aharoni amir.aharoni at gmail.com
Wed Aug 15 02:16:06 PDT 2007

It's a very simple question, consider it a sanity check:

How can i check that a value is present in a list?

In Perl 6 there's a lovely thing called quantum:

my $set = any(1, 2, 3, 4, 5);
if (3 == $set) {
    say "found";

It is not found in Perl 5.8. There's a CPAN module called
Quantum::Superpositions that emulates this. Maybe it will be present
in Perl 5.10.

Now, what is the simplest way to do it in Perl 5.8 without CPAN modules?

Isn't there anything better than this:

my @set = (1, 2, 3, 4, 5);
foreach (@set) {
    if (3 == $_) {
        print "found\n";

Or is there some builtin or standard library function that i am missing?

grep may be clever, but it iterates over the whole list, and i don't need it.

The Perl Cookbook suggests using a hash if i just need to test for the
presence of an element in a list. I can create a hash with just keys
and empty values:

my %set = (
    'a' => '',
    'b' => '',
    'c' => '',
if (exists $set{'a'}) {
    print "found\n";

However, using a hash without values is a bit counterintuitive. Or
maybe i can write it in a more readable way?..

Also, can there be significant performance or memory optimizations if
i use a hash instead of a loop on large sets? (I am talking about many
megabytes of data.)

Amir Elisha Aharoni
my band: http://www.myspace.com/tzabari/
my blog: http://aharoni.wordpress.com/

More information about the Perl mailing list