#!/usr/local/bin/perl $\ = "\n"; # keep count of each word in a hash %words = (); # keep number of words per line in an array @wordcount = (); open(FH,"sherlock.txt"); while($line = ) { chomp $line; # split line at whitespace (i.e. into words) @words = split(/\W/,$line); # iterate through all words in the line $wordcount = 0; for $word (@words) { if($word =~ /\w/) { # increment count for this word $words{$word}++; $wordcount++; } } # add number of passed words in this line to the array push @wordcount, $wordcount; } $wordcount_total = 0; for $i (0..@wordcount-1) { $wordcount_total += $wordcount[$i]; print qq(line $i had $wordcount[$i] words); } print qq(saw ),scalar(@wordcount),qq( lines in file); print qq(saw $wordcount_total words in file); print qq(average words per line ),$wordcount_total/@wordcount; @words_common = sort { $words{$b} <=> $words{$a} } keys %words; @words_length = sort { length($b) <=> length($a) } keys %words; for $i (0..4) { print qq(common word $i $words_common[$i]); } for $i (0..4) { print qq(longest word $i $words_length[$i]); } close(FH);