为什么我在比较 Perl 中输入的行时遇到问题?
我不知道这个简单的事务我可能做错了什么,但它不起作用:
print "OK? (y or n)\n";
$ans = <>;
print "\n";
if($ans eq "y"){print $ans;}
我基本上想知道如何测试用户输入。 这点代码对我来说不起作用。 如果用户输入了 y
,我只是尝试打印 $ans
。
有什么建议么?
编辑:-我也尝试过单引号
I don't know what I could be doing wrong with this simple transaction, but it's not working:
print "OK? (y or n)\n";
$ans = <>;
print "\n";
if($ans eq "y"){print $ans;}
I basically want to know how to test the user input. This little bit of code won't work for me. I'm just trying to print $ans
if y
is entered by the user.
Any suggestions?
EDIT: - I have also tried single quotes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你有没有尝试过:
?
Have you tried:
?
尽管您的直接问题已得到解答,但您可能需要查看替代方案,例如 Term::Readline
Although your direct question has been answered, you may want to look at alternatives like Term::Readline
解决神秘内容变量的万能药:
A cure-all for variables of mysterious content:
你做错了几件事。
(1) 当您需要时,不要使用菱形运算符 (<>)。 钻石操作员还会从 @ARGV 读取文件,您可能不希望这样做。
(2) $ans 永远不会等于“y”,除非你先 chomp 它。 它的末尾会有一个换行符。
You're doing a couple things wrong.
(1) Don't use the diamond operator (<>) when you want <STDIN>. The diamond operator will also read files from @ARGV, which you probably don't want.
(2) $ans will never be equal to "y" unless you chomp it first. It will have a newline at the end.