1

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

THANK YOU, coming from C++, I had no idea perl requires the newline marker to specify. Also thank you for explaining more how <STDIN> works
@Manny C++ also requires the newline character, == is exact. However, cin only reads up to the first whitespace character so it does not read the newline. <filehandle> reads the whole line.
@Manny Also, don't do this while ($dif == 1). $quit ne $choice might happen to return 1, but it is documented to return true. Instead just check if it's true: while($dif). It's a common mistake to check for 0 or 1 instead of false and true.
@Manny, Re "I had no idea perl requires the newline marker to specify.", To specify what, then end of the line? That's the definition of a line. Then end of the string? No, a LF does not indicate the end of a string, nor is it needed at the end of string. You read a line that contained a LF, and you didn't remove it (e.g. by using chomp). It has nothing to do with Perl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.