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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.