Paul Lalli said:
No, please do *not* try grep for an "in" operator. Please *do* read
the relevant FAQ on this subject:
perldoc -q contains
Found in /opt/perl/lib/5.6.1/pod/perlfaq4.pod
How can I tell whether a list or array contains a certain
element?
That FAQ will explain to you why you should NOT use grep just to
determine if an element is contained in an array.
Feh.
Please do not use
($is_there) = grep $_ eq $whatever, @array;
or worse yet
($is_there) = grep /$whatever/, @array;
These are slow (checks every element even if the first
matches), inefficient (same reason), and potentially buggy
(what if there are regex characters in $whatever?).
Feh. Perl is slow and inefficient. Unless you have an unusual structure
to your data-usage, the difference in loops for this operation is on
average a factor of 2. Unless this is in the inner-most loop of your code,
that probably isn't worth batting an eye at. It is not like a difference
between NlnN and N**2. And actually grep might be faster, because the
implicit low-level loop of grep is probably faster than the explicit
Perl-level loop, and because a query not in the array/list requires both
methods to traverse all elements--so if there are a substantial number of
misses, even the theoretical factor of 2 goes out the window. Finally,
grep will generally be inline, while the other way will probably require a
subroutine call with its overhead.
"Potentially buggy"? Yes, if you use a regex to test for equality, which
common sense would tell you not to use, I guess it wouldn't do what you
want. You can screw up any code if you put your mind to it. You could
also put a regex rather than an equality test in the code that the FAQ
recommends. So what?
Either use the explicit loop-and-return-on-found,
7 lines of code to replace 1? What is more likely to have a bug sneak
in?
convert your
structure to a hash, or use the List::Util function first()
I whole heartedly agree on the hash, but List::Util is even more
"potentially buggy". What happens if you search for and find the empty
string?
Xho