Rafaqat Ali Chaudhry 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;
Others have mentioned why grep() is a bad idea here. Why are you using a regex here? Assuming your looking at numbers, dont' you want a numeric equality test like $x == $y > 6. if (@matches) { > 7. $l_status="TRUE"; > 8. } > 9. else { > 10. $l_status="FALSE"; > 11. } > 12. return $l_status; Using "TRUE" and "FALSE" as return codes is unconventional. You can't use these in Perl boolean expressions. Do they have some other use in your program? > 13. } > > The Way I call it: > > 1. $check=checkNumber($num1); > > The array has at least 20K elements. This piece of code is taking up > almost 100% of the CUP cycles. Would somebody please suggest some > alternative solution. If the array needs to be searched repeatedly, consider constructing a hash. Then you can do direct lookups. Or, look into using mjd's Memoize module to cache results so repeated tests are faster. A more efficient iterative approach using a numeric equality test would be: sub checkNumber { $_[0] == $_ && return 1 for @numbers; return; } This returns 1 for a match and undef for no match. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]