How can I get if .. else to work?

Viewed 157

I wrote a Perl program where the user should type in a user name. If they enter admin, they should see the message

Welcome, admin!

Otherwise the console output should be

The username is incorrect

Here is my code

use utf8;

print "Username: ";

$username = <STDIN>;

if ( $username eq "admin" ) {
    print "Welcome, admin!";
}
else {
    print "The username is incorrect.";
}

But whatever the user inputs the program goes on to the else branch.

Why does this happen?

5 Answers

Whenever you are not sure why a comparison fails, make sure you know what's in your variable:

use Data::Dumper;
local $Data::Dumper::Useqq = 1;
print Dumper $variable;
# print Dumper \@array;
# print Dumper \%hash;

like @ikegami suggested, you need to use chomp:

chomp $username;

perldoc -f chomp

The empty <> operator is usually the best choice for input. It will read data from any files named on the command line, or from the keyboard if there were none

Your $username = <STDIN> will read from the keyboard, and if you enter admin and the enter key it will contain "admin\n". So you need to chomp the LF character from the end of the input

You should also use strict and use warnings 'all' at the start of every Perl program

Like this

use strict;
use warnings 'all';

print "Username: ";
my $user_name = <>;
chomp $user_name;

if ( $user_name eq 'admin' ) {
    print "Welcome, admin!\n";
}
else {
    print "The username is incorrect\n";
}

The comparison never succeed because you don't remove the line feed created by pressing Enter. Use chomp!

As everyone else already mentioned, you have a line feed and chomp will sort that out. In the rare event however where a user perhaps types a space before admin, it will still fail. You can therefore use left and right trim

use strict;
use warnings 'all';

print "Username: ";
my $user_name = <>;
$user_name =~ s/^\s+|\s+$//g;

if ( $user_name eq 'admin' ) {
     print "Welcome, admin!\n";
}
else {
    print "The username is incorrect\n";
}

which will match admin followed by newline, space or tab before and space or tab after admin.

You are missing to use chomp. When user has entered admin, it translated to admin\n, so we need to remove that \n.
chomp is used to remove the $/ variable (line feed character) which is set to mostly \n (new line). $/ is the input record separator, newline by default.

use utf8;

print "Username: ";

$username = <STDIN>;
chomp $username;
if ( $username eq "admin" ) {
    print "Welcome, admin!";
}
else {
    print "The username is incorrect.";
}
Related