[Israel.pm] Is there an operator like IN in perl

Shlomi Fish shlomif at iglu.org.il
Wed Mar 4 06:09:57 PST 2009


On Wednesday 04 March 2009 15:27:04 Amir E. Aharoni wrote:
> 2009/3/4 Berler Chanan <chananb at centerity.com>:
> > Hi All,
> >
> > I wonder why/or should I ask "if" there is an operator IN in perl.
> > For example:
> >
> > my @arr = (1,2,3,4,5);
> > if (1 in @arr)
> > {
> >    # do something
> > }
>
> grep will work, but its performance may be slower if you are looking
> for only one list member.
>
> If you have Perl 5.10, use ~~ :
>
> =================================================
> use 5.010;
>
> my @beatles = qw(John Paul George Ringo);
>
> if ('George' ~~ @beatles) {
>     say 'George is in Beatles';
> }
> if ('Amir' ~~ @beatles) {
>     say 'Amir is in Beatles?!'; # This is not printed
> }
>
> =================================================
>

My problem with this code is that it's hard to tell whether ~~ will do numeric 
or string comparison.

> If you don't have Perl 5.10, use List::Util:
>
> =================================================
> use List::Util 'first';
>
> my @beatles = qw(John Paul George Ringo);
>
> if (first { $_ eq 'George' } @beatles) {
>     print "George is in Beatles\n";
> }
> if (first { $_ eq 'Amir' } @beatles) {
>     print "Amir is in Beatles?!\n"; # This is not printed
> }
>

This will be problematic if you're looking for an element that's false in 
Perl. 

Like:

{{{{{{{{
if (first { $_ == 0 } (100,0,30))
}}}}}}}}

For these cases, any from List::MoreUtils would be preferable.

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Interview with Ben Collins-Sussman - http://xrl.us/bjn8s

<mauke>    I'm not interested in what you're doing; what are you trying to 
           achieve?
<PerlJam>  mauke: I'm trying to achieve world peace and this regex is
           the last thing standing in my way! ;)




More information about the Perl mailing list