You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  • chomp isn't modifying the original variable: When you run chomp($g) inside the elsif condition, it only removes the newline temporarily for that single comparison—but the actual $g variable 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 $g to 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

  1. Moved chomp to the top: Right after reading input, we clean up $g by removing the newline—so all subsequent comparisons use the correct string/number value.
  2. Reordered checks: We first handle exit commands to avoid invalid string-to-number comparisons and ensure the quit logic runs first.
  3. Added input validation: A regex check ensures the user enters a valid number (or exit command) to prevent warnings and confusion.
  4. Used last to exit: When the user types quit/exit, last breaks out of the loop immediately instead of continuing the game logic.
  5. Fixed the syntax error: Removed the extra closing brace at the end.

内容的提问来源于stack exchange,提问作者masral

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:33