显示代码本身的短脚本?



想知道是否有可能编写一个简短的脚本,在最后将代码本身打印出来并计算行数。即使是一些简单的东西,比如几行

#!/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, '<', $0);
while (<$f>){print};
print "read $. linesn";

变量$0$PROGRAM_NAME保存了程序的名称。

或者(每行都有linecount)

use warnings;
use strict;
print "Hello there";
print "This got me scratching my headn";
open (my $f, '<', $0);
while (<$f>){printf "%03d %s",$., $_};
print "read $. linesn";

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

看到perlvar

也可以参考mobs的答案,了解使用DATA

读取文件的方法。

正在执行的脚本的名称在变量$0中,因此完成此操作的直接方法是

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

$0因为您更改了目录或覆盖了它而不可用时,另一个选项是使用特殊的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__
...

最新更新