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

前端 未结 10 1384
醉酒成梦
醉酒成梦 2020-12-31 03:21

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

10条回答
  •  萌比男神i
    2020-12-31 03:48

    A variation on bmdhacks' answer that will probably produce better results is to use \s+ (or even better \W+) as the delimiter. Consider the string "The  quick  brown fox" (additional spaces if it's not obvious). Using a delimiter of a single whitespace character will give a word count of six not four. So, try:

    open(FILE, ") {
        $lines++;
        $chars += length($_);
        $words += scalar(split(/\W+/, $_));
    }
    
    print("lines=$lines words=$words chars=$chars\n");
    

    Using \W+ as the delimiter will stop punctuation (amongst other things) from counting as words.

提交回复
热议问题