Adetque has asked for the wisdom of the Perl Monks concerning the following question:
I'm fairly new to Perl, so this shouldn't be very hard to answer.
Anyway, I'm working on a function to return a hash with how often each word occurs in a text file. I have a regex for things that shouldn't be part of a word (such as whitespace and parentheses) to determine where a word ends and a new word starts. However, I found that when there's a line that has no text on it other than a newline, it adds the newline to the hash as it would with a word, and I have no idea how to fix this, nor if it's a problem with read or my regex. Here's my code:
#!/usr/bin/perl use strict; use warnings; sub readWords { ## Gets how many of each word are in a file and returns a hash my $file = shift; my %words = (); my $currentWord = ""; # What characters to ignore my $blacklist = '[\s~`!@#\$%\^&\*\(\)\{\}\+=\\\/\[\]\.\,<>\?;:"]'; open(my $FILE, "<", $file) or die("$0: $file: $!\n"); while(!eof($FILE)) { while(read($FILE, my $letter, 1)) { if($letter !~ /$blacklist/) { $currentWord .= lc($letter); } else { last; } } if(!defined($words{$currentWord})) { $words{$currentWord} = 0; } $words{$currentWord}++; $currentWord = ""; } close($FILE); return %words; } sub main() { my %words = readWords($ARGV[0]); my @keys = keys(%words); my @commonWord = ("", 0); foreach my $key (sort(@keys)) { if($words{$key} > $commonWord[1]) { @commonWord = ("$key", $words{$key}); } print("$key: $words{$key}\n"); } print("Number of unique words: " . scalar(@keys) . "\n"); print("Most common word: $commonWord[0] - used $commonWord[1] time +s\n"); } main();
Thanks in advance if you decide to help.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: The read function and newlines
by roboticus (Chancellor) on Jul 03, 2010 at 19:57 UTC | |
by Adetque (Initiate) on Jul 03, 2010 at 20:23 UTC | |
by roboticus (Chancellor) on Jul 03, 2010 at 20:28 UTC | |
|
Re: The read function and newlines
by chromatic (Archbishop) on Jul 04, 2010 at 03:04 UTC | |
by BrowserUk (Patriarch) on Jul 04, 2010 at 03:29 UTC | |
by chromatic (Archbishop) on Jul 04, 2010 at 08:03 UTC | |
by BrowserUk (Patriarch) on Jul 04, 2010 at 11:49 UTC |