Home > database >  How Do You Compare Strings in Perl?
How Do You Compare Strings in Perl?

Time:07-29

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);

CodePudding user response:

$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.

  • Related