On Tue, 29 Jul 2003, Rafaqat Ali Chaudhary wrote:
> Dear all,
>
> I've a function which searches a given number from an array and returns
> the result.
>
> Function:
>
> 1. sub checkNumber($)
> 2. {
> 3. my ($l_number) = @_;
> 4. my $l_status;
> 5. my @matches= grep { /$l_number/ } @numbers;
The grep function will look through all elements in @numbers
and return all elements that match the pattern.
Since you are only looking for the first match, a foreach loop
will do just fine.
Also, using the regular expression /$l_number/ will search
for the number as a string in @numbers.
That means that you will get TRUE, if @numbers contains ('101')
and the number you are searching for is 1.
One way of doing it is,
$l_status = 'FALSE';
foreach (@numbers)
{
if ($_ == $l_number)
{
$l_status = 'TRUE';
last;
}
}
Or, for the memory conscious,
(since foreach involves loading all elements into memory)
$l_status = 'FALSE';
for (my $i=0; $i < @numbers; $i++)
{
if ($numbers[$i] == $l_number)
{
$l_status = 'TRUE';
last;
}
}
Bye,
George P.
> 6. if (@matches) {
> 7. $l_status="TRUE";
> 8. }
> 9. else {
> 10. $l_status="FALSE";
> 11. }
> 12. return $l_status;
> 13. }
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]