3

I'm not sure what mistake I'm making, but I just changed ne to != and it worked.

This is a simple program to let the user guess a number until they hit a target number.

#!/usr/bin/perl

my $guess = 1;

do {
    $guess = <STDIN>;
} while ( $guess != 12 ) ; # it doesn't work if i replace != with ne

say "you guessed ", $guess;
1
  • Welcome to Stack Overflow. Please take the tour and read [how to ask]. Your first question was well-written and well-received. Now that you have a good answer that obviously helped you, the next step is to mark it as accepted so visitors can later see that it solved the problem.
    – simbabque
    Jan 9, 2017 at 13:31

1 Answer 1

13

Perl's ne is the string not-equal operator, so $guess and 12 are treated as strings.

A string obtained via <> contains a newline character at the end, so it is not equal to the string '12'.

!= is the numeric not-equal operator, so both operands are treated as numbers. In this case Perl will ignore any trailing non-numeric characters when making the conversion, so the newline is ignored and the string 12<newline> is treated as numeric 12.

Were you to chomp the obtained value before comparison, the ne operator would also work.

1
  • 2
    Since this involves user input it may be good to mention possible trailing spaces as well.
    – zdim
    Jan 9, 2017 at 5:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.