Why can't I match my string from standard input in Perl?

Why will my script not work correctly?

I follow a YouTube video and worked for the guy.

I am running Perl on Windows using ActiveState ActivePerl 5.12.2.1202

Here is my tiny tiny code block.

print "What is your name?\n";
$name = <STDIN>;
if ($name eq "Jon") {
print "We have met before!\n";
} else {
print "We have not met before.\n";
}

The code automatically jumps to the else statement and does not even check the if statement.


Solution 1:

The statement $name = <STDIN>; reads from standard input and includes the terminating newline character "\n". Remove this character using the chomp function:

print "What is your name?\n";
$name = <STDIN>;
chomp($name);
if ($name eq "Jon") {
  print "We have met before!\n";
} else {
  print "We have not met before.\n";
}

Solution 2:

The trick in programming is to know what your data are. When something's not acting like you expect, look at the data to see if they are what you expect. For instance:

 print "The name is [$name]\n";

You put the braces around it so you can see any extra whitespace that might be there. In this case, you would have seen:

The name is [Jon
]

That's your clue that there is extra stuff. Since the eq has to match exactly, it fails to match.

If you're just starting with Perl, try Learning Perl. It's much better than random videos from YouTube. :)

Solution 3:

When you read the name standard input as $name = <STDIN>;

$name will have a trailing newline. So if I enter foo , $name will actually have foo\n.

To get rid of this newline you an make use of the chomp function as:

chomp($name = <STDIN>);