1

Possible Duplicate:
How do I compare two strings in Perl?

Why does this script always return "You won"?

print "Choose heads or tails :\n";
$answer = <STDIN>;
chomp $answer;

if( $answer == "heads" ) {
    print "You won\n";
}
else {
    print "Moron! You lost.\n"
}

And what should be the correct code for the same?

Community
  • 1
  • 1
Exorcist
  • 252
  • 2
  • 3
  • 15
  • 1
    http://stackoverflow.com/questions/1175390/how-do-i-compare-two-strings-in-perl – j0nes Sep 08 '12 at 09:59
  • And `use strict;`. They would have alerted you to that problem (Argument "heads" isn't numeric in numeric eq (==)) and that you haven't declared your `$answer` variable before using it. – Quentin Sep 08 '12 at 10:00
  • 2
    "Argument "heads" isn't numeric" would have come from `warnings`, not `strict`. – Dave Sherohman Sep 08 '12 at 17:25

1 Answers1

14

String comparation in Perl uses eq instead of ==. Try:

if ($answer eq "heads")

If you are comparing numbers you use ==.

Read more about it in a post at perlmonks.

When learning Perl I suggest you start your scripts with use strict; and use warnings;. That way you will get a warning for this kind of operation. And it will also help you with misspelled variables.

Qiau
  • 5,976
  • 3
  • 29
  • 40
  • I used strict for other programs. In one, I took an input from user in the following format : '$n=;' and I got an error like this - 'It requires explicit package name.' Got the same error for loop variables also. Can you elaborate on the same? – Exorcist Sep 08 '12 at 10:20
  • 1
    Declare variables using `my` before them. I.e. `my $n;` or `my $n = ;` – Qiau Sep 08 '12 at 10:21
  • 3
    @Exorcist - what resources are you using to learn Perl? Some are pretty old and out of date. – DVK Sep 08 '12 at 11:49
  • 2
    @Exorcist, we keep a list of [good tutorials](http://perl-tutorial.org/) (and bad) to help newcomers learn the right way. Perl has been around a long time and many of the old (bad) tutorials still exist out on the interwebs. Pick one of these good ones and continue learning. :-) – Joel Berger Sep 08 '12 at 13:53
  • @Qiau-Whats the use of `my`? @DVK-I am using Strawberry Perl. @Joel Berger- Can you please look at this question : http://stackoverflow.com/questions/12546239/learning-perl-for-web-designing – Exorcist Sep 22 '12 at 17:49