解决方法
$ARGV Contains the name of the current file when reading from <> .
但也要考虑$.在perlvar.如果使用perl -n执行此操作,则可能不会以您想要的方式显示,因为在perl -n用例中计数器不会重置.
06001
Current line number for the last filehandle accessed.
Each filehandle in Perl counts the number of lines that have been read
from it. (Depending on the value of$/
,Perl’s idea of what
constitutes a line may not match yours.) When a line is read from a
filehandle (viareadline()
or<>
),or whentell()
orseek()
is called
on it,$.
becomes an alias to the line counter for that filehandle.You can adjust the counter by assigning to
$.
,but this will not
actually move the seek pointer. Localizing$.
will not localize the
filehandle’s line count. Instead,it will localize perl’s notion of
which filehandle$.
is currently aliased to.
$.
is reset when the filehandle is closed,but not when an open
filehandle is reopened without an interveningclose()
. For more
details,see I/O Operators in perlop. Because<>
never does an
explicit close,line numbers increase across ARGV files (but see
examples in eof).You can also use
HANDLE->input_line_number(EXPR)
to access the line
counter for a given filehandle without having to worry about which
handle you last accessed.Mnemonic: many programs use “.” to mean the current line number.
以下是一个例子:
$perl -nE 'say "$.,$ARGV";' foo.pl bar.pl 1,foo.pl 2,foo.pl 3,foo.pl 4,foo.pl 5,foo.pl 6,foo.pl 7,foo.pl 8,foo.pl 9,foo.pl 10,foo.pl 11,foo.pl 12,foo.pl 13,bar.pl 14,bar.pl 15,bar.pl
如果要重置,您需要在读取循环结束时检查eof(感谢@Borodin).另见perldoc for eof
:
$perl -nE 'say "$.,$ARGV"; close ARGV if eof' foo.pl bar.pl