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; 6. if (@matches) { 7. $l_status="TRUE"; 8. } 9. else { 10. $l_status="FALSE"; 11. } 12. return $l_status; 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.
Thanks in Advance
Rafaqat Ali Chaudhary
You can improve the code largely by just returning immediately as you get a match
( dont use grep when you dont need it )
sub check { my ($l_number) = @_ foreach ( @numbers) { return 'TRUE' if($_ == $l_number); } return 'FALSE'; }
So every false condition would have gone thru all elements but every true condition will return immediately
Besides if you are doing this check a lot many times in your program It may be better to create a hash array. Hash arrays are implemented real good in perl
then you can use
In the main script put
my %hash = (); @[EMAIL PROTECTED]();
so you can check directly
if(exists($hash{$l_number})) {
...... # this is TRUE ....
} else {
........ # this is FALSE ....
}
The Hash method will take more memory but will be much quicker
Thanks Ram
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]