一个家伙Stackoverflower 试图@ARGV在他的END街区使用,但无法.
为什么@ARGV仅BEGIN使用以下单行在块内定义:
$ perl -lne 'BEGIN{ print "BEGIN" if @ARGV }
print "MIDDLE" if @ARGV }
{ print "END" if @ARGV ' file
BEGIN
Run Code Online (Sandbox Code Playgroud)
perldoc perlrun对此事没有任何启示.这里发生了什么?
首先,数组不能是未定义的.您正在检查数组是否为空.要理解为什么它被清空,你需要理解-n.-n用你的代码包围你的代码
LINE: while (<>) {
...
}
Run Code Online (Sandbox Code Playgroud)
这是短的
LINE: while (defined($_ = <ARGV>)) {
...
}
Run Code Online (Sandbox Code Playgroud)
ARGV是一个神奇的句柄,可以读取列出@ARGV的文件,在打开文件名时将其移出.
$ echo foo1 > foo
$ echo foo2 >>foo
$ echo bar1 > bar
$ echo bar2 >>bar
$ echo baz1 > baz
$ echo baz2 >>baz
$ perl -nlE'
BEGIN { say "Files to read: @ARGV" }
say "Read $_ from $ARGV. Files left to read: @ARGV";
' foo bar baz
Files to read: foo bar baz
Read foo1 from foo. Files left to read: bar baz
Read foo2 from foo. Files left to read: bar baz
Read bar1 from bar. Files left to read: baz
Read bar2 from bar. Files left to read: baz
Read baz1 from baz. Files left to read:
Read baz2 from baz. Files left to read:
Run Code Online (Sandbox Code Playgroud)
请记住,BEGIN块一经编译就会执行,因此在<ARGV>执行BEGIN块时尚未执行(即使它出现在程序的前面),因此@ARGV尚未修改.
-n在perlrun中记录.ARGV,@ARGV并$ARGV记录在perlvar中.