http://qs321.pair.com?node_id=667742


in reply to How do I count the frequency of words in a file and save them for later?

this script counts the occurrence of each word present in the file and print a summary.
#!/usr/bin/perl -w use strict; use IO::File; my %seen=(); my $file_name="/home/myprog/matter"; my $file=IO::File->new("< $file_name") or die "Couldn't open $file_nam +e for reading:$! \n"; my $line; while(defined($line=$file->getline())) { foreach my $word (split / /,$line) { chomp($word); if ($word =~ /\w+/) { $word =~ s/[. ,]$//; if ($seen{$word}) { my $count; $count=$seen{$word}; $count=$count+1; $seen{$word}=$count; } else { $seen{$word}=1; } }# if ($word =~ /\w+/) end here } # foreach my $word (split / /,$line) end here } # while(defined($line=$file->getline())) print "\n =============== o/p Word and it's count frequency=========== +============="; foreach my $val (keys %seen) { print "\n $val => $seen{$val}"; } $file->close();
Let me know if any changes are required.

Originally posted as a Categorized Answer.