I know this is a FAQ, and I know the answer(s) in the FAQ.
.
.
.index ("@array", $sought) > -1;
Please note, however, that isn't one of the suggested methods that is in the FAQ. ;-)
I disagree with the FAQ in this case. Often, grep is exactly what you want. If grep isn't good enough, then you probably chose the wrong data structure in the first place. (The FAQ also shows a C-ish example of hopping out of a loop when an element is found. Even though that halves your number of comparisons on average, it's still O(N); given that grep is quick, for small arrays, it probably isn't worth it.)
As far as doing it this way, well... you've already gotten some responses that outline the issues. As dws said, if it is a single character you are looking for, then no problem. (What he didn't mention was that if it is a single character you are looking for, then you might be better off using tr// instead of index().)
You can use it for longer data if you no a particular substring will never show up in the data. For obvious reasons, it's best if that substring is short, like a single character. A good choice might be "\0". Once you choose your substring, you have to set $" appropriately and you still have to be careful...Some examples of what to watch for:
Here's how to make it work:@a = qw( food bar baz ); $" = "\0"; print "Found\n" if index "@a", qq/foo/; # Wrongly succeeds. print "Found\n" if index "@a", qq/foo$"/; # Rightly fails. print "Found\n" if index "@a", qq/$"bar$"/; # Rightly succeeds... print "Found\n" if index "@a", qq/$"baz$"/; # Wrongly fails.
In words, you have to tack the delimiter on to both the front and back of both the string you are searching through and the one you are searching for.print "Found\n" if index qq($"@a$"), qq/$"foo$"/;
Not only is it a mess, stringifying the array might use a lot of memory if the array is big... and if the array isn't big, you aren't really buying yourself much.
Conclusion: In most cases, grep will do fine. If it won't choose a better data structure. If that isn't an option, write a loop and bail out after finding the first match. But there's no good reason to use index on a stringified array, IMHO.
-sauoq "My two cents aren't worth a dime.";
In reply to Re: Is X in my array?
by sauoq
in thread Is X in my array?
by Not_a_Number
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |