in reply to Attempting to fill a hash

There are a few style related things that may help. First, always use strictures (use strict; use warnings;). They give an early warning about a number of common types of error.

You hardly ever need to explicitly count things in Perl so you don't need to maintain $wordcount in the loop.

Always use the three parameter open. It's safer and explicit about the open mode. Good to see you testing the open result by the way!

Keep variables as local as possible. Note in the sample below that $deadstring is local to the loop (why that name btw?).

Your off by one in $wordcount was probably due to a blank line. Better to test for that in the loop.

Here's a reworked version of your code. Note that the "file" is actually a string variable. That's a really useful trick for samples like this so you don't need a "real" file.

use strict; use warnings; my $wordlist = <<WORDS; a the cat mat sat WORDS my $userinput = "myexample"; my $wordfile = '/home/psychohamster/Desktop/Desktop_Stuff/AnagramWor +dList'; my %hashlist; open my $wordhandle, '<', \$wordlist or die "Unable to open WordList: +$!"; while (my $deadstring = <$wordhandle>) { chomp $deadstring; next unless length $deadstring; $hashlist{$deadstring} = 1; } my $wordCount = keys %hashlist; if ($wordCount) { print "Found $wordCount words:\n"; print join "\n", sort keys %hashlist, ''; } else { print "Didn't find any words\n"; }

Prints:

Found 5 words: a cat mat sat the

Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: Attempting to fill a hash
by TwistedTransistor (Novice) on Jun 06, 2008 at 01:32 UTC
    GrandFather,
    Thank You.
    First off thank you for that little tip on word lists, very nice.
    Two things
    1. next unless length $deadstring; - I'm assuming this is to make sure that $deadstring is not an empty variable.
    2. Worked perfectly when I tried it with the word list. However, once I tried using the actual file, it started reading the data wrong again. Is it possible that the coding of the file is causing the streamreader to interpert it wrong for perl?

      next unless length $deadstring; uses a statement modifier (the unless bit) which is rather like an if statement backwards. You can use if, unless, for and while as statement modifiers.

      Try copying and pasting from your file into the sample code where the word list is. If that shows the error you see with the real file then post the modified sample here. If it doesn't show the same error then most likely your editor is modifying the text somewhat. One possibility is that the file has different line endings than are native on your system. For example, you may have got the file from a *nix system and are running it under Windows or vis-versa.


      Perl is environmentally friendly - it saves trees