在Perl中使用空stdin终止while循环

在Perl中使用空stdin终止while循环,perl,Perl,我正在Perl脚本中运行一个while循环,当没有为stdin输入任何内容时,该脚本需要终止。我尝试过各种可能性,最近一次是$ne,但没有任何效果。如果给定的条件stdin为nothing,在提示下按enter键,则终止while循环的正确方法是什么 编辑:为了澄清,我需要一个类似于下面代码的循环,如果没有为提示输入任何内容,我需要终止while循环 print "Enter your information: "; $in = <>; while($in) { #do s

我正在Perl脚本中运行一个while循环,当没有为stdin输入任何内容时,该脚本需要终止。我尝试过各种可能性,最近一次是$ne,但没有任何效果。如果给定的条件stdin为nothing,在提示下按enter键,则终止while循环的正确方法是什么

编辑:为了澄清,我需要一个类似于下面代码的循环,如果没有为提示输入任何内容,我需要终止while循环

print "Enter your information: ";
$in = <>;

while($in) {
    #do stuff

    print "Enter your information: ";
    $in = <>;
}

您已经介绍了其他两个答案,但要更完整地复制代码,您可以执行以下操作:

use strict;
use warnings;

while (1) {
    print "Enter your information: ";
    my $in = <STDIN>;
    chomp($in);

    last if $in eq '';
}

我想你在找这个

while () {

  print "Enter your information: ";
  chomp(my $in = <>);
  last unless $in;

  # do stuff with $in
}
试试这个

#!/usr/bin/env perl

use warnings;
use strict;

my $in = '';
while (1) {
  print "Enter your information: ";
  $in = <STDIN>;

  ##  do something with $in, I assume

  last if $in =~ /^\s*$/;     # empty or whitespace ends
}
但您可能会尝试附加行,在这种情况下,会发生更改

$in = <STDIN>;

或者嚼一嚼,然后加上

或者,您可能正在寻找一种更普遍的方式来过滤交互式提示:

#!/usr/bin/env perl

use warnings;
use strict;

sub prompt {
  my ($text, $filter) = @_;
  while (1) {
    print $text;
    my $entry = <STDIN>; 
    chomp $entry;
    return $entry if $entry =~ $filter;
  }
}

prompt "Enter a digit: ", qw/^\d$/;

没关系,这正是它应该做的。非常感谢。这个解决方案并没有做任何简单的while{…}不会doOP提到的词法和stdinI只是用更多信息更新了主帖子;不幸的是,这不起作用。其他信息是否有助于解决我的问题?@mpapec:Understanted:\n是真的。我已经修复了我的答案。最后除非$in-如果用户输入0,这将退出循环。如果用户输入文件结尾,这将无休止地循环请告诉我,如何输入文件结尾?我能确定的唯一边缘情况是,如果有人输入了Ctnl-Z,他们将使用未初始化值警告。如果他们足够关心,他们可以做//来解决这个问题,但鉴于这个问题的性质,我认为解决这个问题不够重要。
$in = <STDIN>;
$in .= <STDIN>;
#!/usr/bin/env perl

use warnings;
use strict;

sub prompt {
  my ($text, $filter) = @_;
  while (1) {
    print $text;
    my $entry = <STDIN>; 
    chomp $entry;
    return $entry if $entry =~ $filter;
  }
}

prompt "Enter a digit: ", qw/^\d$/;