0

我想问如何在 Perl 中计算行数。

例子:

文件 a.txt

ikhsan
faqih 
kamal 
jundi
iqbal

文件 b.txt

ikram
izzul
ibnu
qoyyim

问题是如何在 Perl 中计算 2 个文件中的所有行。

如果我只想读取一个文件,我的代码是:

这是我的data.txt

a
b
c
d

我的代码

open (FILE, "data.txt") or die "Can't open file: $!";

my ($lines) = (0);
while (<FILE>) {
  $lines++;
  print $lines;

如果我执行: perl countlines.pl

C:\perl> perl countlines.pl
4
C:\perl>

我的问题如何计算 2 个文件中的所有行?

4

2 回答 2

2

这适用于任意数量的文件

perl -lne 'END { print $. }' a.txt b.txt

这个怎么运作

使用 -ln 标志,perl 被编译为如下脚本:

BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    sub END {
        print $.;
    }
    ;
}

这会循环给定文件列表中的所有文件,并且什么都不做!

但是有一个特殊的 perl 变量$.,它是读取的行数的计数器

所以在脚本的最后,这会被打印出来,显示文件中的总行数

于 2013-06-30T07:53:07.723 回答
1

我建议使用自动表单<>

$count++ while <>;
print $count;

用法:

perl countlines.pl a.txt b.txt

如果您想手动完成,您可以重复您的过程:

my ($lines) = (0);
open (FILEA, "a.txt") or die "Can't open file: $!";
while (<FILEA>) { $lines++; }
open (FILEB, "b.txt") or die "Can't open file: $!";
while (<FILEB>) { $lines++; }
于 2013-06-30T06:12:34.537 回答