Perl的钻石运算符(空文件句柄)目前正在读取哪个文件?

前端之家收集整理的这篇文章主要介绍了Perl的钻石运算符(空文件句柄)目前正在读取哪个文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Perl的钻石运算符从命令行上指定的文件读取.

我想能够报告消息,例如“$FILENAME $$的麻烦”,但是如何知道钻石目前使用哪个文件

解决方法

perlvar
$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 (via readline() or <> ),or when tell() or seek() 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 intervening close(). 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
原文链接:https://www.f2er.com/Perl/172449.html

猜你在找的Perl相关文章