Word Counting


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



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

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



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() {
push @words, split;
print "found ".scalar(@words)." words in filen";
found 7 words in file



[tags]Perl Coding School[/tags]


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 *