2009/3/4 Berler Chanan <[email protected]>:
> 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
}
=================================================
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
}
=================================================
--
Amir Elisha Aharoni
heb: http://haharoni.wordpress.com | eng: http://aharoni.wordpress.com
cat: http://aprenent.wordpress.com | rus: http://amire80.livejournal.com
"We're living in pieces,
I want to live in peace." - T. Moore
_______________________________________________
Perl mailing list
[email protected]
http://perl.org.il/mailman/listinfo/perl