Manny
Manny

Reputation: 43

How do you compare strings in Perl?

Practicing Perl for the first time today. I want to loop until a user types "quit". Entering "quit" does not stop and it is an infinite loop. Am I using string comparison wrong? I have this originally:

do 
{
    print "Enter a sentence or phrase to convert or 'quit': ";
    $choice = <STDIN>;  # user input variable
} while ($choice ne "quit");

I also tried creating a separate variable to store and check for in the do-while loop but still an infinite loop:

$quit = "quit";

do 
{
    print "Enter a sentence or phrase to convert to or 'quit': ";
    $choice = <STDIN>;  # init user input variable
    $dif = $quit ne $choice;
} while ($dif == 1);

Upvotes: 1

Views: 155

Answers (1)

Schwern
Schwern

Reputation: 165606

$choice = <STDIN> reads a line from stdin including the newline at the end.

You either need to check for "quit\n" or remove the newline with chomp.

Upvotes: 3

Related Questions