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

Berler Chanan bc.other at gmail.com
Wed Mar 4 06:21:26 PST 2009


Hi All,

All are good answers but:

1) I can't use any of the perl modules, or should I say use the minimum
possible.
2) Using hash is great but I looked for more suite and elegant solution
3) I wonder why nobody asked about this simple operator on old version (ps:
I currently using 5.8 means I can't use ~~)

Thanks
Chanan
   

-----Original Message-----
From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On Behalf
Of Shlomi Fish
Sent: Wednesday, March 04, 2009 4:10 PM
To: perl at perl.org.il
Subject: Re: [Israel.pm] Is there an operator like IN in perl

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! ;)

_______________________________________________
Perl mailing list
Perl at perl.org.il
http://perl.org.il/mailman/listinfo/perl




More information about the Perl mailing list