Adetque:
I don't see a way for a newline to be in your list. However, it looks like you'll get an empty string in your hash: You read the file with a newline, the newline is ignored, then you hit the end of the file. So $currentWord is "", which doesn't exist in your hash, so it's added. You'll probably want to verify that $currentWord isn't empty before stuffing it into your hash.
Having said that, though, I think I'd just use split to get your list of words and enter them into the hash--something like this (untested):
sub readWords {
## Gets how many of each word are in a file and returns a hash
my $file = shift;
my %words = ();
# What characters to ignore
my $blacklist = qr{[\s~`!@#\$%\^&\*\(\)\{\}\+=\\\/\[\]\.\,<>\?;:"]
++};
open(my $FILE, "<", $file) or die("$0: $file: $!\n");
while(my $currentline = <$FILE>) {
$words{$_}++ for split $blacklist, $currentline;
}
close($FILE);
return %words;
}
...roboticus
Update: I just tested the function and it works. A couple observations, though:
- You're returning a hash, but you may want to consider returning a hash reference instead.
- Your blacklist still allows some non-word characters in it (e.g. ' and _). You might want to use:
my $blacklist = qr{\W+};
- The function allows an empty string to be added, so you might want to add (before the return statement):
delete $words{''};
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.