in reply to in function?

This is best done using a hash instead of an array. But if you only have an array to begin with, it's easy to convert.
(Warning, untested code below)

# assume your array is still in myarray; set up a hash foreach (@myarray) { $myhash{$_} = 1; } # now, test for the existence of 'blah' if ($myhash{'blah'}) { do_something(); }
If you use a hash instead of an array everywhere, you can also save the one-time overhead of setting up the hash in the first place. Using a hash makes the test closer to unit time than linear, which can speed things up significantly if you have a lot of array elements, or if you're doing a lot of "in"-like tests.

Alan

Replies are listed 'Best First'.
RE: Re: in function?
by SuperCruncher (Pilgrim) on Jul 08, 2000 at 15:35 UTC
    A more succinct (but semantically equivalent) version of:
    foreach (@myarray) { $myhash{$_} = 1; }
    is
    $myhash{$_}++ for @myarray;
    I once heard (somewhere) that doing
    if ($myhash{'blah'}) { do_something(); }
    (i.e. refering to a key in a hash) causes that key to come into existence, so the above expression may always evaluate as true. I haven't been able to prove this, but I think what you want is the exists function:
    if (exists($myhash{'blah'})) { # Do something here }
    I quite like using 'exists', it makes code far more readable.