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

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...