Word Counting

[problem]

You want to count the words in a file, using Perl.

[/problem]

[solution]

Obviously wc -w can be used for this under UNIX.

But fairly decent demo on the power of split and push! 🙂

[/solution]

[example]


while(<>) { push @words, split; }

print "found ".scalar(@words)." words in filen";

Works nicely, even over multiple lines:


[marcus@bree]/var/log/httpd% echo "test 1 23 4 n a b c" | perl -e 'while() {
chomp();
push @words, split;
}
print "found ".scalar(@words)." words in filen";
'
found 7 words in file

[/example]

[reference]

[tags]Perl Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *