MSPM5 has asked for the wisdom of the Perl Monks concerning the following question:

When typing == i always got "good choice" but when i typing "eq" always print bad choice

#!/usr/bin/perl print "what is your name\n"; $name = <STDIN>; print "hello $name"; print "select letter\n"; $select = <STDIN>; if ($select == a) { print "good choice\n"; } else { print "bad choice\n"; }

I wanna do something like if i type "a" print good choice else bad choice but i don't know where the problem is ?

Replies are listed 'Best First'.
Re: What i doing wrong
by stevieb (Canon) on Apr 01, 2012 at 20:29 UTC

    Because == evaluates 'a' in numeric context. eq is used for alpha comparisons, but it will never match because $select still has a newline character (\n) appended from the input.

    #!/usr/bin/perl use warnings; use strict; print "what is your name: "; chomp( my $name = <STDIN> ); print "hello $name\n"; print "select letter\n"; chomp( my $select = <STDIN> ); if ($select eq 'a'){ print "good choice\n"; } else { print "bad choice\n"; }
    Outputs:
    what is your name: steve hello steve select letter a good choice
Re: What i doing wrong
by toolic (Bishop) on Apr 01, 2012 at 22:09 UTC
      That will him add my's in front of the variables, quote the a, and (maybe) use "eq" (but he's already done that, and that didn't do what he expected it to do).

      It's not going to solve his error (not chomping).

      Using strict and warnings isn't a silver bullet. In a rare case, it solves a problem. In that rare case, posting "use strict; use warnings;" is a useful answer. Most of the time, it's not.

      This is a "most of the time" case.

        I decided to test your assertion that use strict;use warnings; would not help this OP. When I ran the OP's code with strict and warnings after adding 'my' where needed I got the following:

        Bareword "a" not allowed while "strict subs" in use at 962926.pl line +10. Execution of 962926.pl aborted due to compilation errors.

        That is one thing it would have helped with. So I added quotes to get the code below. Have a look at the warnings I got then. Clearly would have been helpful. Probably a 'good choice'.

        #!/usr/bin/perl use strict; use warnings; print "what is your name\n"; my $name = <STDIN>; print "hello $name"; print "select letter\n"; my $select = <STDIN>; if ($select == 'a') { print "good choice\n"; } else { print "bad choice\n"; }
        Argument "a" isn't numeric in numeric eq (==) at 962926.pl line 10, <S +TDIN> line 2. Argument "a\n" isn't numeric in numeric eq (==) at 962926.pl line 10, +<STDIN> line 2. good choice