为什么我在比较 Perl 中输入的行时遇到问题? [英] Why am I having trouble comparing lines from input in Perl?
问题描述
我不知道这个简单的交易我可能做错了什么,但它不起作用:
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;}
我基本上想知道如何测试用户输入.这一点代码对我不起作用.如果用户输入了 y
,我只是想打印 $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.
有什么建议吗?
-我也试过单引号
推荐答案
你做错了几件事.
(1) 当您需要 <STDIN> 时,不要使用菱形运算符 (<>).菱形操作符还会从 @ARGV 读取文件,您可能不想要.
(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 永远不会等于 "y" 除非你先砍掉它.最后会有一个换行符.
(2) $ans will never be equal to "y" unless you chomp it first. It will have a newline at the end.
这篇关于为什么我在比较 Perl 中输入的行时遇到问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!