写作时

#!/usr/bin/perl -w
use strict;

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    <>;
}
每次<!>之后

返回<!>;我得到一行。

为什么我不能在每个<!>之后使用下一个脚本返回<!>返回<!>一段?

#!/usr/bin/perl -w
use strict;

local $/ = "";

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    <>;
}

__DATA__
line one
line two
line three
line four
line five

line six
line seven
line eigth
line nine

line ten
line eleven
line twelve
有帮助吗?

解决方案

在你的第一个脚本中,将$ /变量设置为默认<!>“; \ n <!>”,<!> lt; DATA <!> gt;只会一次返回一行。

我相信第二个脚本会做你想要的,只是<!> lt; <!> gt;不会在'return'上终止读取,而是在<!> lt; ctrl-d <!> gt;由于你的$ /设置(正如其他人指出的那样<!> lt; <!> gt;从STDIN读取但我认为你已经知道并正在使用它来调节输出。)

如果你真的想用'return'来规范输出,那么你需要在循环中用$ /做更多的事情。

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    $/ = "\n"; # default so that the following terminates the read on 'return'
    <>;
    $/ = ""; 
}   

其他提示

我猜你期待这一行

local $/ = "";

改变

的行为
<DATA>

继续阅读直到数据结束。

但事实上它需要这样的东西

{
    local $/;  # $/ becomes undef in this block
    ...
}

启用 slurp mode (以及将该模式包含在{curlys}内的范围内。

实际上它是在说“<!>”;忘记将换行符视为记录结束标记<!>;,

除此之外......你的代码中还有一个 tie fighter

while( <DATA> ) {
    print "\n-------------------------\n\n";
    print;
    <>;    # <-- Feel the power of the DARK SIDE!!!
}

这个小家伙会从STDIN读取,而不是从DATA读取 - 这真的是你想要的吗?

使用<!> lt; <!> gt;段落模式中的这种方式(交互式)将会令人困惑。点击<!>后返回<!>返回<!> ;;相反,它将读取,直到它得到非空行(段落的开头),然后读取,直到它得到一个空行(该段落的结尾),然后继续读取,直到它得到一个非空行(开始以下段落 - 将被缓冲,不返回)所以它知道它被丢弃了任何额外的空行。

也许你应该使用:

local $/ = "\n"; <>
而在你的循环结束时

。或者POSIX :: getchar()。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top