显示代码本身的简短脚本?

Short script that displays the code itself?

想知道是否可以编写一个简短的脚本,在最后打印代码本身并计算行数。即使是简单的几行

#!/usr/bin/perl

use strict;

print "Hello there";
print "This got me scratching my head";

并且输出将是此代码本身以及计算的行数。 提前致谢。

是这样的吗?

use warnings;
use strict;

print "Hello there";
print "This got me scratching my head";

open (my $f, '<', [=10=]);
while (<$f>){print};
print "read $. lines\n";

变量 [=12=]$PROGRAM_NAME 保存程序的名称。

或者(每行有行数)

use warnings;
use strict;

print "Hello there";
print "This got me scratching my head\n";

open (my $f, '<', [=11=]);
while (<$f>){printf "%03d %s",$., $_};
print "read $. lines\n";

变量 $.$INPUT_LINE_NUMBER 包含上次访问的文件句柄的当前行号。

perlvar

另见 使用 DATA

读取文件的方法

正在执行的脚本的名称在变量 [=12=] 中,因此实现此目的的直接方法是

...
open(my $ZERO,"<",[=10=]);
my @lines = <$ZERO>;
close $ZERO;
print @lines, "count = ", 0+@lines, "\n";
...

[=12=] 由于您更改目录或覆盖它而无法使用时,另一种选择是使用特殊 DATA 句柄,该句柄在包含特殊 __END__ 的文件上打开或 __DATA__ 个代币。

...
seek DATA, 0, 0;   # seek to begin of file, not begin of __DATA__ section
my @lines = <DATA>;
print @lines, "count = ",0+@lines,"\n";
...
__DATA__
...