如何使用Perl计算文件中的字符,单词和行?

Noa*_*ahD 17 perl file counting

使用Perl(不使用wc)计算文本文件的字符数,单词数和行数的好/最佳方法是什么?

bmd*_*cks 25

这是perl代码.计算单词可能有些主观,但我只是说它是任何不是空格的字符串.

open(FILE, "<file.txt") or die "Could not open file: $!";

my ($lines, $words, $chars) = (0,0,0);

while (<FILE>) {
    $lines++;
    $chars += length($_);
    $words += scalar(split(/\s+/, $_));
}

print("lines=$lines words=$words chars=$chars\n");
Run Code Online (Sandbox Code Playgroud)

  • 对于字数,你想要:标量(分裂); 这将拆分/\s + /并删除前导空字段,就像awk一样. (3认同)
  • @Paul Tomblin:在这里,你现在开心吗:perl -ne'END {print"$.$ c $ w \n"} $ c + = length; $ w + = split' (2认同)

Nic*_*son 7

bmdhacks答案的变体可能会产生更好的结果是使用\ s +(甚至更好的\ W +)作为分隔符.考虑字符串"快速棕色狐狸"(如果不明显则增加空格).使用单个空格字符的分隔符将使字数为6而不是4.所以,试试:

open(FILE, "<file.txt") or die "Could not open file: $!";

my ($lines, $words, $chars) = (0,0,0);

while (<FILE>) {
    $lines++;
    $chars += length($_);
    $words += scalar(split(/\W+/, $_));
}

print("lines=$lines words=$words chars=$chars\n");
Run Code Online (Sandbox Code Playgroud)

使用\ W +作为分隔符将停止标点符号(除其他外)作为单词计数.