code is not working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blackgoat
    New Member
    • Jan 2010
    • 33

    #1

    code is not working

    Hi!

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

    Code:
    %dbase = {
            apple => "fruit",
            brinjal => "vegetable" ,
            coffee => "beverage",
            };
    
    my @info;
    
    $info[0]="lemon";
    $info[1]="juice";
    
    $result = validate($info[0],$info[1]);
    
    sub validate
         {
            my $usr = @_[0];
            my $pwd = @_[1];
            
            while (($u, $p) = each %dbase)
                {  
                  if ($usr == $u && $pwd == $p)
                        { return(1);
                          break;
                        }
                  else
                        { return(0); }
                }
         }    
    
    
    {print "$result"};
    Thanks

    BG
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    There are multiple errors in your script.
    1. the way you have defined hash
    Code:
    %dbase = { 
            apple => "fruit", 
            brinjal => "vegetable" , 
            coffee => "beverage", 
            };
    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:
    Code:
    %dbase = (
            apple => "fruit", 
            brinjal => "vegetable" , 
            coffee => "beverage", 
            ); 
      
    my @info; 
      
    $info[0]="lemon"; 
    $info[1]="juice"; 
      
    $result = validate($info[0],$info[1]); 
      
    sub validate 
         { 
            my $usr = @_[0]; 
            my $pwd = @_[1];         
            my $r=0;
            while (($u, $p) = each %dbase) 
                {             
                  if ($usr eq $u && $pwd eq $p) 
    
                        {                       
                          $r=1;
                          last; 
                        } 
                  else 
                        { 
    $r=0; } 
           }     
      return $r     }     
        
    print "$result\n";

    Comment

    • blackgoat
      New Member
      • Jan 2010
      • 33

      #3
      okay... Thanks a lot!

      Comment

      Working...