Re: Is item in array
- From: rvtol+news@xxxxxxxxxxxx (Dr.Ruud)
- Date: Sun, 31 Dec 2006 12:50:43 +0100
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.
--
Affijn, Ruud
"Gewoon is een tijger."
.
- Follow-Ups:
- Re: Is item in array
- From: Mathew Snyder
- Re: Is item in array
- References:
- Is item in array
- From: Mathew Snyder
- Re: Is item in array
- From: Ken Foskey
- Is item in array
- Prev by Date: Re: What's being thrown away?
- Next by Date: Re: Is item in array
- Previous by thread: Re: Is item in array
- Next by thread: Re: Is item in array
- Index(es):
Relevant Pages
|