如何将自动递增数字添加到数组?

Rah*_*ikh 1 arrays perl file

我正在通过以下代码读取perl中的文件内容

my @files = glob("$PATH/*");
foreach my $file (@files){
    open(MYFILE,"<$file");
    my @fileContent = <MYFILE>;
    close(MYFILE);
}
Run Code Online (Sandbox Code Playgroud)

现在,我想在每行前加上自动递增数.就像是 -

fileContent[0] = 1: This
fileContent[1] = 2: is
fileContent[2] = 3: a
fileContent[3] = 4: text
fileContent[4] = 5: file.
Run Code Online (Sandbox Code Playgroud)

有人知道这样做的有效方法吗?

谢谢!

TLP*_*TLP 10

单行怎么样?

perl -wne 'print "$.: $_"; close ARGV if eof;' path/*
Run Code Online (Sandbox Code Playgroud)

或者在脚本内部,使用数组:

use strict;
use warnings;
use autodie;

while (<tmp/data*>) {
    open my $fh, '<', $_;
    my @fileContent;
    push @fileContent, "$.: $_" while <$fh>;
}
Run Code Online (Sandbox Code Playgroud)

这里有文档$. .

  • 如果你需要格式化数字(例如,到某个宽度),你也可以使用[`sprintf`](http://perldoc.perl.org/functions/sprintf.html),我建议你查看[ perlvar](http://perldoc.perl.org/perlvar.html)有关`$ .`的更多信息. (2认同)