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.
In reply to The read function and newlines by Adetque
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |