views:

197

answers:

4

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

A: 

Have you tried:

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

?

rogeriopvl
yeah... sure have
CheeseConQueso
+13  A: 

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.

Matt Kane
thank you, why the eff does it tag on a \n? because i hit enter to register my answer? it should auto-chomp if you ask me...
CheeseConQueso
You have the "why" correct. I'm sure there is something in http://perldoc.perl.org/perlvar.html that will allow auto-chomping or something.
Matt Kane
No, Perl will not autochomp, though Cheese is right it should in most cases. I think Perl 6 does autochomp by default.
Leon Timmermans
You do *not* want to autochomp if you have to tell the difference between reading a line terminated with \n vs. a partial line ending because of EOF (line ending because of EOF may signal a user abort or a partially flushed file.)
vladr
You can tell Perl to autochomp by specifying "#!/usr/bin/perl -l" on the first line. But the effect is global, so only do this if your script is tiny.
j_random_hacker
j_random_hacker: -l's autochomping only applies to the implicit readline created by -n or -p, not to any other readline, so it's not a global effect you need to be wary of.
ysth
+1  A: 

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

Joe Casadonte
+5  A: 

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