Re: Is item in array



Dr.Ruud wrote:
Ken Foskey schreef:
Mathew Snyder:

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.

That still involves iterating and comparing each element, but now done
(faster) by grep.

If the array is already sorted, a binary search would be the way to go.

Otherwise you can use a loop that short-circuits by using "last" if the
item is found.


With smallish arrays, you can even use index(), after stringizing it:

$string = join $;, ('', @array, '');
index($string, "$;$item$;") >= 0 and print "found\n";

or use a regular expression:

$string = join "\n", @array;
/^$item$/m and print "found\n";


You might be wanting a hash table not an array.

Yes, that is the best answer. Especially if multiple items need to be
tested.


I ended up using hashes for what I needed. Thanks for the input.

Mathew
.



Relevant Pages

  • Re: Is item in array
    ... Look up grep. ... That still involves iterating and comparing each element, ... If the array is already sorted, a binary search would be the way to go. ...
    (perl.beginners)
  • Re: Find a line in a text file then print a field
    ... Here is "grep" part of my perl script so far (ommitting the various ... the matching lines in an array. ...
    (perl.beginners)
  • Re: Text Script
    ... more overhead than reading from an array as it is an in-memory operation. ... > Rewinding a file might indeed be instantaneous as you say, ... > comparing apples to oranges here. ... and the simplicity of using the dictionary object. ...
    (microsoft.public.windows.server.scripting)
  • Re: How to sort an array which contains a value several times ?
    ... Jay Savage a e'crit: ... > because we want to iterate over @array and filter duplicates out (you ... > cases $is_new remains 0 and grep filters that element out. ...
    (perl.beginners)
  • Re: Re: How to sort an array which contains a value several times ?
    ... > because we want to iterate over @array and filter duplicates out (you ... > cases $is_new remains 0 and grep filters that element out. ...
    (perl.beginners)