Why am I having trouble comparing lines from input

2019-07-21 22:12发布

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

4条回答
爷的心禁止访问
2楼-- · 2019-07-21 22:55

Have you tried:

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

?

查看更多
聊天终结者
3楼-- · 2019-07-21 22:57

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);
查看更多
手持菜刀,她持情操
4楼-- · 2019-07-21 23:01

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

查看更多
唯我独甜
5楼-- · 2019-07-21 23:09

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.

查看更多
登录 后发表回答