Perl中if语句无法捕获quit/exit字符串输入问题排查
Hey there! Let's fix your number guessing game where the quit/exit commands aren't triggering. The main issues are how you're handling chomp and the order of your checks. Here's what's going wrong and how to fix it:
Key Issues in Your Code
chompisn't modifying the original variable: When you runchomp($g)inside theelsifcondition, it only removes the newline temporarily for that single comparison—but the actual$gvariable still has the newline character attached. So comparing it to "quit" or "exit" (which don't have newlines) will never match.- Check order is backwards: You're first comparing
$gto the random number before checking for exit commands. If the user types "quit", this triggers a warning (since you're comparing a string to a number) and skips the exit check entirely. - Extra closing brace: Your code has an extra
}at the end that will cause a syntax error.
Fixed Code
use strict; use warnings; my $g = 0; my $rn = int(rand(25)); until ($g == $rn) { $g = <STDIN>; chomp $g; # Chomp first to strip the newline from input # First check for exit commands before handling number logic if ($g eq "quit" || $g eq "exit") { print "Exiting the game...\n"; last; # Break out of the until loop immediately } # Validate input is a number before comparing elsif ($g !~ /^\d+$/) { print "Please enter a valid number, or 'quit'/'exit' to leave.\n"; next; # Skip to the next loop iteration } elsif ($g == $rn) { print "You got it!\n"; } elsif ($g > $rn) { print "Incorrect, it's lower.\n"; } elsif ($g < $rn) { print "Incorrect, it's higher.\n"; } }
What Changed
- Moved
chompto the top: Right after reading input, we clean up$gby removing the newline—so all subsequent comparisons use the correct string/number value. - Reordered checks: We first handle exit commands to avoid invalid string-to-number comparisons and ensure the quit logic runs first.
- Added input validation: A regex check ensures the user enters a valid number (or exit command) to prevent warnings and confusion.
- Used
lastto exit: When the user typesquit/exit,lastbreaks out of the loop immediately instead of continuing the game logic. - Fixed the syntax error: Removed the extra closing brace at the end.
内容的提问来源于stack exchange,提问作者masral
相关产品推荐
相关产品推荐

