perl-收集所有stdin,直到空白线或EOF



如何从stdin行中收集所有行直至空白行或EOF,以先到者为准。看起来像:

 my @lines;
 while(<> ne EOF || <> not blank) {
      chomp;
      push(@lines, $_);
 }

停止在EOF或空白行上读取输入,我更喜欢此解决方案:

while (<>) {
    last unless /S/;
    # do something with $_ here...
}

与Mob的解决方案不同,这不会给出"使用非专业化值$ _模式匹配(m//)

如果"空白"行意味着内部的字符,只是新线n(UNIX)或rn(Windows),然后使用

my @lines;
/^$/ && last, s/r?n$//, push(@lines, $_) while <>;

(请参阅此演示)


如果"空白"行应该内部有多个白色空间,例如"         ",则使用

my @lines;
/^s*$/ && last, s/r?n$//, push(@lines, $_) while <>;

这只会检查eof:

while (<>) {
    s/s+z//;
    push @lines, $_;
}

因此,您需要添加空白行:

while (<>) {
    s/s+z//;
    last if $_ eq "";
    push @lines, $_;
}

或者,

while (<>) {
    s/s+z//;
    push @lines, $_;
}

的缩写
while (defined( $_ = <> )) {
    s/s+z//;
    push @lines, $_;
}

因此,如果您想要在while条件下的整个条件,则将使用

while (defined( $_ = <> ) && /S/) {
    s/s+z//;
    push @lines, $_;
}

折断EOF或空白行:

while ( ($_ = <>) =~ /S/ ) {
   chomp;
   push @lines, $_;
}

/S/测试输入是否包含任何非Whitespace。

最新更新