http://www.perlmonks.org?node_id=1004978

melb100 has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perl monks,

I am trying to write a script that will allow me to count words for each individual line of a file (the file contains 64 sentences, so I would like 64 different word counts, next to the relevant sentence).

I am brand new to Perl and so far have managed to cobble together the following, which gives me total words in the file, lines in the file, characters in the file, average words per line, average characters per word, and even characters per line(including spaces), but now I have come to you as I cannot work out how I get a word count for each line.

#!/usr/local/bin/perl #MB Nov 2012 #script to check experiment stimuli #counts the number of lines in a file #counts number of words in a file and averages across lines #count the number of characters in a file and averages across words #BUT how do I count the number of words ON EACH LINE? while (<>) { chop; foreach $w (split) { $words++; $char = $char + length($w); #cumulative characters for all words } #$wordline = length($_); # this gives the character count per line ins +tead of the word count; } #print "\n$. the sentence [$_] has $words words"; # this prints the se +ntence(good!) but counts the cumulative number of words for all sente +nces until that point instead of that sentence only print "\n$words words in this file\n"; $avwds = $words/$.; #average words per line $avch = $char/$words; #average characters per word print "there are $char characters in total"; print "\nthere are $. lines with an average of $avwds words per line"; print "\nthere are $words words with an average of $avch characters pe +r word";

I feel as though I should be able to make a list of words in each line, and then I could count the length of that list for each line, but I am not sure how to do this and how to integrate it with the foreach word loop I already have.

Any advice or pointers appreciated,

madeleine