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

Amir E. Aharoni amir.aharoni at gmail.com
Thu Aug 16 04:14:10 PDT 2007


On 16/08/07, Shlomi Fish <shlomif at iglu.org.il> wrote:
> On Thursday 16 August 2007, Ran Eilam wrote:
> > On 8/15/07, Ran Eilam <ran.eilam at gmail.com> wrote:
> > > On 8/15/07, Shlomi Fish <shlomif at iglu.org.il> wrote:
> > > > use List::MoreUtils qw(any);
> > > > my @set = (1, 2, 3, 4, 5);
> > > > if (any { $_ == 3 } @set) {  print "found\n" }
> > >
> > > Is best, and it's core.
> >
> > Correction: not best, and not core. Review your posts!
> >
> > List::Util::first is both.
> >
>
> Well, you're right that List::MoreUtils is not core and List::Util is.
> However, why is "first" preferable over "any"? I think "any" would be
> preferable here, because we're not interested in the first item that matches,
> just if it exists. And "any" probably short-circuits.

Thanks, everyone.

List::MoreUtils is probably the best if i want to (unfortunately) avoid CPAN.

I can use the returned value in boolean context and i'll get the
expected results, BUT there will be a problem if the searched value is
an empty string or the string '0', which are false. So, to be on the
safe side, it's better to use defined:

use strict;
use warnings;

use List::Util 'first';

my @set = qw(Reuven Shimon Levi Yehuda 0);

my $found_levi         = defined(first { $_ eq 'Levi' } @set);
my $found_levi_defined = defined(first { $_ eq 'Levi' } @set);
my $found_zero_value   =         first { $_ eq 0      } @set;

if ($found_levi) {
    print "Levi found - ok\n";
}
else {
    print "Levi not found - not ok\n";
}

if ($found_levi_defined) {
    print "Zero found with defined - ok\n";
}
else {
    print "Zero not found with defined - not ok\n";
}

if ($found_zero_value) {
    print "Zero found with value - ok\n";
}
else {
    print "Zero not found with value - not ok\n";
}

exit;



More information about the Perl mailing list