开发者

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

开发者 https://www.devze.com 2023-01-17 01:27 出处:网络
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

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.


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";
}


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. :)


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>);
0

精彩评论

暂无评论...
验证码 换一张
取 消