<>
操作符从命令行指定的文件中读取。我想报告消息,例如
"在文件$FILENAME的第$.行出现问题"
,但是如何确定当前由diamond使用的文件?<>
操作符从命令行指定的文件中读取。"在文件$FILENAME的第$.行出现问题"
,但是如何确定当前由diamond使用的文件?参见perlvar:
$ARGV
Contains the name of the current file when reading from <> .
同时也要考虑在 perlvar
中的 $.
。如果你使用 perl -n
命令,可能不会按照你想要的方式执行,因为在 perl -n
的使用情况下计数器没有被重置。
$.
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 关于 eof
。$ perl -nE 'say "$., $ARGV"; close ARGV if eof' foo.pl bar.pl
close ARGV if eof
。这将重置$.
为零。 - Borodin
eof
。 - Guidobot.pm
扩展名的源文件,不需要安装过程。默认情况下,@INC
将当前目录包括在内,因此只需将必要的文件复制到与源文件相同的目录中即可使包可用并满足依赖关系。 - Borodin