为什么我在比较 Perl 中输入的行时遇到问题?

发布于 2024-07-15 00:46:03 字数 277 浏览 9 评论 0原文

我不知道这个简单的事务我可能做错了什么,但它不起作用:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

演多会厌 2024-07-22 00:46:03

你有没有尝试过:

if($ans eq 'y'){print $ans;}

Have you tried:

if($ans eq 'y'){print $ans;}

?

九公里浅绿 2024-07-22 00:46:03

尽管您的直接问题已得到解答,但您可能需要查看替代方案,例如 Term::Readline

Although your direct question has been answered, you may want to look at alternatives like Term::Readline

半枫 2024-07-22 00:46:03

解决神秘内容变量的万能药:

use Data::Dumper;
$Data::Dumper::Useqq = 1; # show newlines, tabs, etc in visible form
$Data::Dumper::Terse = 1;
print '$ans is really: ', Dumper($ans);

A cure-all for variables of mysterious content:

use Data::Dumper;
$Data::Dumper::Useqq = 1; # show newlines, tabs, etc in visible form
$Data::Dumper::Terse = 1;
print '$ans is really: ', Dumper($ans);
樱娆 2024-07-22 00:46:03

你做错了几件事。

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文