#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    18
    Rep Power
    0

    While loop with multiple conditions


    Code:
    while ($answer ne 'y' && $answer ne 'n')
    {
    print "invalid response, Overwrite file(y/n)?";
    $answer = <STDIN>;
    }
    I have this loop in my program, but no matter what I put in, it won't exit the loop. How would I fix it?
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,663
    Rep Power
    1945
    What values does $answer has if you try to print it out after the assignment?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    18
    Rep Power
    0
    Originally Posted by MrFujin
    What values does $answer has if you try to print it out after the assignment?
    if I type n, it prints n. if I type y it prints y.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,940
    Rep Power
    1225
    You need to chomp $answer to remove the line terminator.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,940
    Rep Power
    1225
    You may want to look at using the IO::Prompt - Interactively prompt for user input module.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    833
    Rep Power
    496
    Originally Posted by Fullmetal99012
    Code:
    while ($answer ne 'y' && $answer ne 'n')
    {
    print "invalid response, Overwrite file(y/n)?";
    $answer = <STDIN>;
    }
    I have this loop in my program, but no matter what I put in, it won't exit the loop. How would I fix it?
    Chomp $answer, otherwise it will never be equal to y or n, but to y or n with a carriage return.

    EDIT: Oops, I did not see that Fishmonger answered the same thing before.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    18
    Rep Power
    0
    Originally Posted by FishMonger
    You need to chomp $answer to remove the line terminator.
    How did I miss this. so simple. I am soo dumb.

IMN logo majestic logo threadwatch logo seochat tools logo