Anonymous Monk,
This is a FAQ. Additionally, I wrote a tutorial to accompany the FAQ - see Getting Matching Items From An Array. On a final note, if your numbers are in order - a binary search may be appropriate. If many searches are going to need to be performed and the data isn't going to change in between searches, consider using a parallel hash for fast lookups.
| [reply] |
| [reply] |
If I understand, something like this could help:
my @matched = grep{ /[0-9]/ } @original_array;
Where you can look more into grep as defined in the perl docs for the grep function.
Hope that helps and good luck!
| [reply] [d/l] [select] |
The standard grep caveat applies - you could end up doing more work here than you actually wanted.
From the OP: I want to check an array of numbers for a particular value, and if found do something.
Personally, I read this as, "I'm looking for one value to operate upon." But, in general, if you're only looking for a single occurrence of a value, it's better to use a foreach loop (or another explicit loop - while/for/whatever).
The reason is that the grep doesn't stop. So, for example, if the element you're looking for is the first item in your list, the grep solution will still process the entire list looking for additional instances. If you're using one of the looping constructs, you can perform your operation and last out of it when you find the value you're looking for.
| [reply] |
Homework or not, it is in your best interests to learn and use Super Search.
Nodes such as:
might give you the insight to solve your problem.
HTH,
| [reply] |
print "Found!" if grep {$_ == $val} @arr; | [reply] [d/l] |
@array=qw/2 3 7 5 34/;
$no=13;
if(grep {$_ == $no} @array)
{
print "Condition true";
} else {
print "Condition false";
}
Here I have a array @array, which contains the list of allowed values. $no should be the number you want to check. | [reply] [d/l] [select] |