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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Attempting to fill a hash
by TwistedTransistor (Novice) on Jun 06, 2008 at 01:32 UTC | |
by GrandFather (Saint) on Jun 06, 2008 at 04:00 UTC |