Search code examples
perlmod-perl

Using hash to check flat file for user login


I have a user login that I am working on and I am trying to use a hash key assignment to check a flat file to see if the entered password matches the stored one. However, I don't have a very good idea of what I am doing so some guidance would be awesome. The code that I have provided is working correctly however there are things within it that should be updated to a more modern style of Perl programming, I just don't know how to do that. http://codepad.org/YYGmdknl


Solution

  • Are you saying the code doesn't work? It sure is dirty, but it looks like it should work.

    Fixes:

    use strict;    # Always use this!
    use warnings;  # Always use this!
    
    my $user     = ...;
    my $password = ...;
    
    my %passwords;
    open(my $fh, '<', 'password.txt') or die $!;
    while (<$fh>) {
       chomp;
       my ($user, $password) = split /:/;
       $passwords{$user} = $password;
    }
    close($fh);
    
    if (exists($passwords{$user}) && $password eq $passwords{$user}) {
       print p("Hello"." ".$user);
    } else {
       print p("Login failed.");
    }
    

    But why the hash?

    use strict;
    use warnings;
    
    my $user     = ...;
    my $password = ...;
    
    my $logged_in;
    open(my $fh, '<', 'password.txt') or die $!;
    while (<$fh>) {
       chomp;
       my ($file_user, $file_password) = split /:/;
       if ($user eq $file_user) {
          if ($password eq $file_password) {
             $logged_in = 1;
          }
    
          last;
       }
    }
    close($fh);
    
    if ($logged_in) {
       print p("Hello"." ".$user);
    } else {
       print p("Login failed.");
    }