我的 Perl 脚本出了什么问题?
下面是我的代码,基本上,如果答案是“Y”,那么脚本会运行一条消息,如果是其他内容,则脚本会关闭。
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
Below is my code, basically if the answer is "Y" then the script runs a message if it's something else then it closes.
#! usr/bin/perl
print "Do you wish to run Program? [Y/N]:";
$answer = <>;
if($answer == "Y") {
print "COOOL\n";
} else {
system "exit"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您正在使用数字 == 来比较字符串。
您可能想使用“eq”:
正如其他人建议的那样,您需要删除末尾的换行符。使用
chomp
。You are using a numerical == to compare your strings.
You probably want to use "eq":
And as others have suggested you'll want to remove the newline at the end. Use
chomp
.除了 chomp/chop 和
eq
与==
之外,您还需要记住答案的大小写。您正在测试大写“Y”,我敢打赌您正在输入小写“y”,并且它们不相等。我建议使用:或使用uc。
Besides the chomp/chop and
eq
vs==
, you also need to keep in mind the case of the answer. You are testing for UPPERCASE 'Y', I'm willing to bet you are entering lowercase 'y' and they are not equal. I would suggest using:or use uc.
如果你问的话,Perl 会准确地告诉你问题是什么。只需将“使用警告”添加到您的代码中即可。
然后运行它,给出:
如果您还添加“使用诊断”,那就更好了。
如果让 Perl 帮助您发现错误,那么用 Perl 编程就会容易得多。
Perl will tell you exactly what the problem is, if you ask it. Just add "use warnings" to your code.
Then running it, gives:
It's even better if you add "use diagnostics" as well.
Programming in Perl is far easier if you let Perl help you find your errors.
删除换行符。
==
用于数字相等,对于字符串,您需要eq
。Remove newline.
==
is for numerical equality, for string you needeq
.当您想知道发生了什么时,请开始跟踪您的输入。确保它是您所认为的那样:
由于您在变量周围放置了大括号,因此您会注意到任何额外的空格。您应该在
$answer
中看到额外的内容:这是您需要采取措施来处理该问题的线索。
而且,
严格
和警告
可以帮助您在问题出现之前发现问题。When you wonder what's going on, start tracing your input. Ensure it is what you think it is:
Since you put the braces around the variable, you'll notice any extra whitespace. You should see extra stuff in
$answer
:That's your clue that you need to do something to handle that.
And,
strict
andwarnings
help you find problems before they are problems.也许使用 Term::Prompt 或 IO::Prompt 会更好。不要重新发明轮子:)
Probably it will be better to use Term::Prompt or IO::Prompt. Don't reinvent the wheel :)
您有换行符,
chomp $answer
和
$answer eq "Y"
You have newline character,
chomp $answer
and
$answer eq "Y"