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

Avishalom Shalit avishalom at gmail.com
Wed Mar 4 06:26:32 PST 2009


well, when you do measure, there may be different scenarios
if you have one lists and many checks , then a hash is the way to go,
(and it is an idiom well worth knowing, especially if your list is
dynamic. e.g. you are processing new elements and adding them to the
list, and then checking, counting them ,.)

also, i don't agree that the hash makes the code look weird.
> my %beatles = (
>    John => 'guitar',
>    Paul => 'bass',
>    George => 'sitar',
>    Ringo => 'drums',
> );
it may look less weird with empty strings '' or a checkmark 'v' or a
japanese smiley '_'

> my %beatles ;
>$beatles{$_}='x' for  qw/john paul george ringo/;



2009/3/4 Amir E. Aharoni <amir.aharoni at gmail.com>:
> 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
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
>



-- 
-- vish



More information about the Perl mailing list