1

I began learning Perl yesterday. I have written this code:

print "Please type in your password.\n";
print "Password: ";
chomp($password = <>);
if ($password == "admin")
{
 print "Password is correct!";
}
else
{
 print "Password is incorrect!";
}

When I write "admin" it tells me that the password is correct but when I write every other password it tells me the same thing. It's like the if doesn't execute. What can I do?

3 Answers3

5

The Comparison Operator "==" is used to compare numbers whereas the operator "eq" is used to compare strings.

ushertwice
  • 61
  • 1
4

To compare strings the eq operator is used. I made this mistake often, too.

…
if ($password eq "admin")
…

If you are using the == operator on strings, a number contained in the string is converted: foo goes to zero, 2foo goes to 2

caylee
  • 921
  • 6
  • 12
  • Can you explain how the strings are being cast with the `==` operator such that they're equal? I would expect them to be compared by length with that operator, but that's obviously not the case. – piojo Oct 28 '17 at 08:00
  • 2
    Strings evaluate to the number zero always. Note "2foo" would fail. See https://stackoverflow.com/a/14046696 – caylee Oct 28 '17 at 08:02
  • Oh, thanks! I was mixing the string->number coercion with vector->number coercion. I've been on Perl 6 for a while, so I've forgotten the implicit details, since everything is more explicit in the next generation. – piojo Oct 28 '17 at 08:06
  • Thanks in advance for accepting my answer :) – caylee Oct 28 '17 at 08:11
  • It's not my question--I was trying to write an answer myself before you did, but I got stuck in explaining why the problem occurs. (Hence, my question to you.) Why don't you add that to your main answer above? That way you can not only correct, but teach. – piojo Oct 28 '17 at 08:21
  • 2
    @xanoetux - Strings do **not** always evaluate numerically to 0. A string beginning with a number (such as your "2foo" example) evaluates as the number it begins with: `perl -E 'say "2foo" + 0'` prints `2`, not `0`, and `perl -E 'say "foo" == "2foo" ? "equal" : "not equal"'` says `not equal`. – Dave Sherohman Oct 28 '17 at 09:33
  • 1
    (My preceding comment is in reference to your comment which incorrectly states "Strings evaluate to the number zero always." The actual answer has it right.) – Dave Sherohman Oct 28 '17 at 09:42
  • Yes, I saw that too. But I cannot correct it now. As you said, the answer is clear – caylee Oct 28 '17 at 09:44
2

Perl uses eq instead of == for string comparison.

Change

if ($password == "admin")
{
     print "Password is correct!";
}

To

if ($password eq "admin")
{
     print "Password is correct!";
}
Mark Mucha
  • 1,560
  • 2
  • 12
  • 18