Perl,如何在循环外从标准输入读取?

Perl, how to read from stdin outside a loop?

有些地方我不明白:

in 是一个包含的文件:

1
2
3

foo.pl

use strict;
<>;
print;
<>;
print;
<>;
print;

然后 运行 :

perl foo.pl < in

为什么这个程序没有输出任何东西?

...而这个:

use strinct;
while(<>) {
    print;
}

输出整个文件

因为

while(<>) 

是shorthand为

while($_ = <>) 

这意味着该行被分配给默认变量$_print.

也使用了它

你写了什么:

<>;

不向 $_ 分配任何内容。它只是 void 上下文中的一个 readline,这意味着该值被丢弃并且不会存储在任何地方。因此 $_ 是空的。如果你 use warnings,Perl 会告诉你发生了什么。

Use of uninitialized value $_ in print

如果您手动完成作业,它将起作用:

$_ = <>;

另请注意,您不必重定向文件内容,只需提供文件名作为参数即可:

perl foo.pl in