How do I count the characters, words, and lines in a file, using Perl?

NoahD picture NoahD · Apr 23, 2009 · Viewed 53.4k times · Source

What is a good/best way to count the number of characters, words, and lines of a text file using Perl (without using wc)?

Answer

bmdhacks picture bmdhacks · Apr 23, 2009

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");