jonesd14 has asked for the wisdom of the Perl Monks concerning the following question:
Hello, Monks (first post).
I briefly learned Perl in my Programming Languages course last spring. I thought it was great, but didn't use it much since. I'm wanting to start learning the language again, and learn it correctly. I'm aware that there are many different ways to do anything in Perl, so let me know if anything can be improved or be more "Perl-ish" in my code below:
The point of this code is to read a .txt file and find the most frequently used word, and report the number of times it's used. If there are multiple words used the most frequently, the program just chooses the first match. The program seems to currently work fine, but as I said, please let me know if anything can be improved upon!
## # FILE: mostFreqWord.pl # AUTHOR: Daniel Jones # CREATED: 12/18/2013 # MODIFIED: 21/18/2013 ## die "ERROR: Must enter one file name.\n" unless $#ARGV == 0; open FILE, "<", $ARGV[0] or die "Could not open $ARGV[0] for reading.\ +n"; #the hash to contain the word-count pairs. my %hash; my @lines = <FILE>; #go through each line in the file foreach my $line(@lines){ #skip non-word characters my @words = split /\W+/, $line; #go through each word in the file foreach my $word(@words){ chomp $word; #force all words to lowercase $word = lc $word; #remove beginning/trailing whitespace $word =~ s/^\s+|\s+$//g; my $key = $file.$word; #if the word exists, increment its value. #otherwise, set it to 1. if(exists $hash{$key}){ $hash{$key}++; } else{ $hash{$key} = 1; } } } close FILE; my @values; #get the values from the hash foreach my $key(keys %hash){ push @values, $hash{$key}; } @values = sort @values; my @keys = keys %hash; my $idx = 0; my $bestVal = @values[-1]; my $bestKey; foreach my $key(@keys){ if ($hash{$key} == $bestVal){ $bestKey = $key; last; } } print "The most frequent word in $ARGV[0] is $bestKey, which was seen +$bestVal times.\n";
|
---|