Re: Is item in array




Ken Foskey wrote:
On Sun, 2006-12-31 at 00:54 -0500, Mathew Snyder wrote:
Is there an easy way to determine if an item is in an array without iterating
through the array and comparing each element to the item in question?

Look up grep.

Gah. Sure, please look it up, and read enough to realize it is very
much the *wrong* tool for this job.

To the OP: please read the FAQ *before* posting:
perldoc -q contained
Found in /software/perl-5.8.5-0/pkg/lib/5.8.5/pod/perlfaq4.pod
How can I tell whether a certain element is contained in a
list or array?
<snip>
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?).
<snip>

You might be wanting a hash table not an array.

That, however, is excellent advice.

Paul Lalli

.



Relevant Pages

  • Re: Perl and GROUP by
    ... For Example I have array with first and last names: ... > grep). ... Would you mind checking out the docs for the sortfunction? ...
    (comp.lang.perl)
  • Re: How to list the statement of all var ?
    ... > of an object when the question was about `var' statements? ... And as soon as i will test it for this particular host ... to use an Object object instead of an Array object. ...
    (comp.lang.javascript)
  • Re: Warning on assigning a function-returning-a-pointer-to-arrays
    ... reminder that it's a pointer and not merely a locally declared array ... That would indicate a bug in the compiler, ... int main{ ...
    (comp.lang.c)
  • Re: Pleac: Programming Language Examples Alike Cookbook
    ... decided to send the youngest, Josh, to buy some beer. ... it's not intended to be an array unset. ...
    (comp.lang.tcl)
  • Idle curiosity (ieee bitorder)
    ... >> Where this becomes a problem is the byte array is LITTLE ENDIAN. ... The GCM specification has no concept beyond bit sequences. ... Without naming bits in some way and carefully specifying what we mean by ...
    (sci.crypt)