无限输入循环,直到用户退出Perl

Jus*_*der 0 regex perl loops

如何进入无限输入循环,直到他退出Perl,因为即使进入退出或q后我也无法正确退出代码.非常感谢您的帮助.

do
 {
 &ipdiscover;
 print "enter q or quit to exit";
  my $input=<>;
  chomp($input);
  if($input=="quit")
  exit;
}until(($input eq "quit")||($input eq "q"));
Run Code Online (Sandbox Code Playgroud)

amo*_*mon 5

&ipdiscover - 除非你知道所有副作用,否则永远不要调用这样的函数.如有疑问,请做ipdiscover().

不要将字符串与==运算符进行比较:这会将参数强制转换为数字.如果它看起来不像数字,那么你就得零.所以$input == "quit"很可能对大多数人来说都是如此$input.

但是,该if语句是根据块来定义的,而不是根据语句来定义的(如C中所示).因此,你必须这样做

if ($input eq "quit") {
  exit;
}
Run Code Online (Sandbox Code Playgroud)

或者简写:exit if $input eq "quit";.但是你为什么要那样做呢?exit终止整个程序.

另一方面,until(($input eq "quit")||($input eq "q"))是一个正确的终止条件,一旦你修复了范围,它将按预期工作$input.

我认为你应该做以下事情,因为这会更好地处理输入的结束(例如在Linux上:Ctrl-D,Windows; Ctrl-Z):

use strict; use warnings; # put this at the top of every program!

while(defined(my $answer = prompt("type q or quit to exit: "))) {
  last if $answer eq "q"
       or $answer eq "quit"
}

sub prompt {
  my ($challenge) = @_;
  local $| = 1;  # set autoflush;
  print $challenge;
  chomp( my $answer = <STDIN> // return undef);
  return $answer;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过说这是last迭代来留下循环.