You're going to have to loop through the array in some fashion. Obviously you have to look at each element to determine if it's in your wanted set, right? grep is just a single loop and is probably faster than doing a foreach and pushing the matching elements onto a new array. When in doubt, Benchmark. | [reply] [d/l] [select] |
Ok in that case, would it be possible to have an array as the first input to grep? Basically,I just want to have more than 1 search string.
Modifying the problem a bit, let's say now I want to get the subset that has the subtring 102 or 101 in them.
thanks
| [reply] |
@new = grep /^x10[12]/,@arr;
| [reply] [d/l] |
greping through an array is an O(n) operation, meaning the amount of work being done carries a 1:1 relationship to the amount of data being acted upon. There is no less-costly way of finding all occurrences of some pattern in an array than to actually look at each element in the array to check for the existance of a pattern. No magic here. You could try stirring up a potion of bat wings, lizzard lips and duck poop, and hum an incantation as it boils in a big black pot, but pretty much those days were over a few centuries ago, and nowadays we're stuck with reality.
If this is an operation that you'll be doing frequently on a large and infrequently changing data set, it may be beneficial to presort the string or cache your search results, but that strategy could prove much more costly if your performing the operation relatively infrequently, or on a frequently changing set of data. The theory here is that maybe you could perform a O(n log n) operation once in order to provide O(1) lookups later on. But again, that only makes sense if you are going to be doing enough lookups down the road to justify the costly O(n log n) (or maybe even O(n^2), or worse) operation to begin with, and if you can assure that you won't have to be doing the more costly operation frequently.
The fact is that iterating through a list is not all that epensive, unless you do it a lot. And if you do it a lot, you might need to look at strategies for keeping track of order, or for caching search results.
| [reply] |