Re: Checking a list for a value
- From: krahnj@xxxxxxxxx (John W. Krahn)
- Date: Sat, 11 Feb 2006 13:38:00 -0800
David Gilden wrote:
I would like to loop through 'all' acceptable values in an array (my white list)
then assign a pass or fail value.
In the following code does not accomplish this, it needs to go through the entire list
before assigning a value.
#!/usr/bin/perl
$valToTest = "ac";
@myGoodList = ("10_rater","36_600","ac","cr914","ec12","fairwind");
$testOk = -1;
foreach my $cat (@myGoodList){
if ($cat =~ /$valToTest/) {
$testOk = 1;
next;
} else {
$testOk = -1;
# value not in list
last;
}
}
print "$testOk\n";
I am going to guess that the foreach is not the right way to address this problem.
Thanks for any insight into this problem,
Your logic says to exit the loop on the first array element that DOES NOT
contain the string in $valToTest. You probably want:
my $testOk = -1;
foreach my $cat ( @myGoodList ) {
if ( $cat =~ /$valToTest/ ) {
$testOk = 1;
last;
}
}
However, if you don't mind looping through ALL the elements of the array you
could do it like this:
my $testOk = grep( /$valToTest/, @myGoodList ) ? 1 : -1;
Although the foreach loop is more efficient as it exits the loop when a match
is found.
If you are looking for an exact match then you should use 'eq' instead of the
match operator:
if ( $cat eq $valToTest ) {
John
--
use Perl;
program
fulfillment
.
- References:
- Checking a list for a value
- From: David Gilden
- Checking a list for a value
- Prev by Date: Re: Checking a list for a value
- Next by Date: Re: pseudohash
- Previous by thread: Re: Checking a list for a value
- Next by thread: How to print last line of file?
- Index(es):
Relevant Pages
|