in reply to Attempting to fill a hash

Perhaps a small, complete example (with embedded comments) will help:
% cat AnagramWordList foo bar baz % cat 690557.pl #!/usr/bin/env perl use strict; use warnings; my $wordfile = 'AnagramWordList'; my %hashlist; ### It is a good practice to use the 3-argument form of "open" open my $wordhandle, '<', $wordfile or die "Unable to open WordList: $ +!"; while (<$wordhandle>) { chomp; ### Remove newline character $hashlist{$_}++; ### Add word to hash } close $wordhandle; ### It is a good practice to close the file AS +AP ### Print out contents of hash while (my ($key, $value) = each %hashlist) { print "key=$key, value=$value\n"; } % ./690557.pl key=bar, value=1 key=baz, value=1 key=foo, value=1

Replies are listed 'Best First'.
Re^2: Attempting to fill a hash
by TwistedTransistor (Novice) on Jun 06, 2008 at 01:51 UTC
    Thank you for your assistance.
    I believe I have finally cracked the problem. The file I was using was downloaded, and evidently there is some kind of character attached to the words that is messing up either chomp or reading it period. When I delete a word manually in gedit and retype it then save the file. That word will succesfully load a keyvalue, however all the other words won't. I'm going to attempt to read all the lines into an array and write them back as raw data to fix the file.

      Your file has most likely been written on Windows, and you're reading it on Unix...  You could run

      $ perl -i.bak -pe 's/\r$//' your-wordlist.file

      to remove the extraneous carriage returns.

      Alternatively, filter the file through the crlf PerlIO layer when reading it (as it does happen on Windows by default), i.e.

      open my $wordhandle, "<:crlf", $wordfile or die ...
        Or use the 'dos2unix' util on most Unix like systems
        thank you, that fixed it all, once again I appreciate everyones help in pointing out where my code needed fixing up / rearranging, and for that tip on removing unwanted carriage returns. :-)