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

Shlomi Fish shlomif at iglu.org.il
Wed Aug 15 08:09:22 PDT 2007


On Wednesday 15 August 2007, Amir E. Aharoni wrote:
> 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";
>       last;
>     }
> }
>

Well there's:

<<<<<<<<<<
#!/usr/bin/perl 

use strict;
use warnings;

use List::MoreUtils qw(any);

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

You can also do something similar with first() in List::Util, which is core as 
of 5.8.x.

> 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.

Right.

>
> 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' => '',
> );

A better way to write it would be using map.  And it is preferable to use => 1 
as the values.

> 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?..
>

If you're concerned about that you can use one of the Set modules on CPAN.

> 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.)

Well, a loop is O(N) while a hash is usually better than that. As far as 
memory is concerned a hash is more wasteful. It's hard for me to know how 
significantly it would be.

Regards,

	Shlomi Fish

---------------------------------------------------------------------
Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

If it's not in my E-mail it doesn't happen. And if my E-mail is saying
one thing, and everything else says something else - E-mail will conquer.
    -- An Israeli Linuxer



More information about the Perl mailing list