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

Yosef Meller mellerf at netvision.net.il
Wed Aug 29 16:07:20 PDT 2007


ציטוט Shlomi Fish:
> Hi Ran and all!
> 
> On Thursday 16 August 2007, Shlomi Fish 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.
>>
> 
> I'm still waiting for your response for why this is the case.

Shlomi seems to be right, first() short-circuits too. Here's the code:

sub first (&@) {
   my $code = shift;

   foreach (@_) {
     return $_ if &{$code}();
   }

   undef;
}

And I don't have List::MoreUtils, so I can't compare.




More information about the Perl mailing list