By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,835 Members | 2,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,835 IT Pros & Developers. It's quick & easy.

code is not working

blackgoat
P: 33
Hi!

Pls help! My code is not working! Pls tell me whats wrong with it... it returns value 1 in all cases!!

Expand|Select|Wrap|Line Numbers
  1. %dbase = {
  2.         apple => "fruit",
  3.         brinjal => "vegetable" ,
  4.         coffee => "beverage",
  5.         };
  6.  
  7. my @info;
  8.  
  9. $info[0]="lemon";
  10. $info[1]="juice";
  11.  
  12. $result = validate($info[0],$info[1]);
  13.  
  14. sub validate
  15.      {
  16.         my $usr = @_[0];
  17.         my $pwd = @_[1];
  18.  
  19.         while (($u, $p) = each %dbase)
  20.             {  
  21.               if ($usr == $u && $pwd == $p)
  22.                     { return(1);
  23.                       break;
  24.                     }
  25.               else
  26.                     { return(0); }
  27.             }
  28.      }    
  29.  
  30.  
  31. {print "$result"};
Thanks

BG
Mar 4 '10 #1
Share this Question
Share on Google+
2 Replies


nithinpes
Expert 100+
P: 410
There are multiple errors in your script.
1. the way you have defined hash
Expand|Select|Wrap|Line Numbers
  1. %dbase = { 
  2.         apple => "fruit", 
  3.         brinjal => "vegetable" , 
  4.         coffee => "beverage", 
  5.         }; 
  6.  
Using curly braces will create an anonymous hash(a hash reference). You should use parentheses in this case.

2. The return statement should be after the entire processing. Otherwise, in the first iteration itself it will come out of the subroutine.

3. Use "last" instead of "break".

The modified code that works is as below:
Expand|Select|Wrap|Line Numbers
  1. %dbase = (
  2.         apple => "fruit", 
  3.         brinjal => "vegetable" , 
  4.         coffee => "beverage", 
  5.         ); 
  6.  
  7. my @info; 
  8.  
  9. $info[0]="lemon"; 
  10. $info[1]="juice"; 
  11.  
  12. $result = validate($info[0],$info[1]); 
  13.  
  14. sub validate 
  15.      { 
  16.         my $usr = @_[0]; 
  17.         my $pwd = @_[1];         
  18.         my $r=0;
  19.         while (($u, $p) = each %dbase) 
  20.             {             
  21.               if ($usr eq $u && $pwd eq $p) 
  22.  
  23.                     {                       
  24.                       $r=1;
  25.                       last; 
  26.                     } 
  27.               else 
  28.                     { 
  29. $r=0; } 
  30.        }     
  31.   return $r     }     
  32.  
  33. print "$result\n"; 
  34.  
Mar 4 '10 #2

blackgoat
P: 33
okay... Thanks a lot!
Mar 4 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.