写作时
#!/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
答案 0 :(得分:5)
在第一个脚本中,将$ /变量设置为默认值“\ 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' <>; $/ = ""; }
答案 1 :(得分:3)
我猜你期待这一行
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读取 - 这真的是你想要的吗?
答案 2 :(得分:2)
使用&lt;&gt;段落模式中的这种方式(交互式)将会令人困惑。当你点击“返回”时它不会返回;相反,它将读取,直到它得到非空行(段落的开头),然后读取,直到它得到一个空行(该段落的结尾),然后继续读取,直到它得到一个非空行(开始以下段落 - 将被缓冲,不返回)所以它知道它被丢弃了任何额外的空行。
也许你应该使用:
local $/ = "\n"; <>
而在你的循环结束时。或者POSIX :: getchar()。