Why am I having trouble comparing lines from input

2019-07-21 23:03发布

问题:

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

回答1:

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.



回答2:

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);


回答3:

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



回答4:

Have you tried:

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

?