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

Amir E. Aharoni amir.aharoni at gmail.com
Wed Mar 4 06:09:38 PST 2009


2009/3/4 Shlomi Fish <shlomif at iglu.org.il>:
> On Wednesday 04 March 2009 15:12:48 Berler Chanan wrote:
>> 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
>> }
>
> 1. If you're going to do it often, you should use a hash instead.

Indeed, a hash is a good solution sometimes:

==========================================
my %beatles = (
    John => 'guitar',
    Paul => 'bass',
    George => 'sitar',
    Ringo => 'drums',
);
if (exists $beatles{John}) {
    print "John is in Beatles\n";
}
==========================================

The only problem with this is that sometimes you just don't know what
to put in the values. In this example i had musical instruments, but
sometimes there's just nothing sensible to put there. You can assign
some dummy values, but it may make the code weird.

Also, if performance is important, try all of the solutions that were
proposed here and compare how much time they take. You will see some
surprises...

-- 
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



More information about the Perl mailing list