如何使用Perl计算文件中的字符,单词和行数? [英] How do I count the characters, words, and lines in a file, using Perl?
本文介绍了如何使用Perl计算文件中的字符,单词和行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Perl(不使用wc)计算文本文件的字符,单词和行数的最佳/最佳方法是什么?
What is a good/best way to count the number of characters, words, and lines of a text file using Perl (without using wc)?
推荐答案
这是perl代码。数词可能有点主观,但我只是说这是不是空格的任何字符串。
Here's the perl code. Counting words can be somewhat subjective, but I just say it's any string of characters that isn't whitespace.
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");
这篇关于如何使用Perl计算文件中的字符,单词和行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文