Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'ne' is not working in do-while loop, whereas '!=' works

Tags:

do-while

perl

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;
like image 823
Nag Avatar asked Sep 04 '25 16:09

Nag


1 Answers

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.

like image 137
bipll Avatar answered Sep 07 '25 18:09

bipll