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

Shlomi Fish shlomif at iglu.org.il
Wed Mar 4 07:07:39 PST 2009


On Wednesday 04 March 2009 16:09:38 Amir E. Aharoni wrote:
> 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.

Well, to turn a list into a does-this-value exist predicate I normally do:

{{{
my %does_exist = (map { $_ => 1 } @list_of_values);
}}}

That way, the 1 is a "dummy" true value.

Using a hash as a set of strings is a legitimate, and common, use of it. Doing 
a "colour-of-the-bike-shed" argument on what its values should contain in that 
case is not very useful, and I would suggest to just put "1".

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

Well, it depends on many factors such as the length of the list, the location 
of the niddle, the number of lookups one does, whether the routines are 
written in XS or plain-perl, etc.

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Understand what Open Source is - http://xrl.us/bjn82

<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