BernieC has asked for the wisdom of the Perl Monks concerning the following question:

Why doesn't this work?
my %dict ; my $dict = "d:/perl/words.short" ; open (my $wds, "<", $dict) or die("Can't open wordlist: $!\n") ; my $words = 0 ; foreach my $wd (<$wds>) { $dict{$wd} = 1 ; } say scalar keys(%dict) ; say "got apple" if exists $dict{apple} ;
when I run it I get
D:\Perl>dictest.pl 66384 D:\Perl>

Replies are listed 'Best First'.
Re: Mysterious hash problem
by soonix (Chancellor) on Oct 16, 2023 at 14:26 UTC
      duh. Forgot about the EOLs in the wordlist. that fixed it thanks!
Re: Mysterious hash problem
by dasgar (Priest) on Oct 16, 2023 at 22:16 UTC

    I'm not sure how your input file is generated/populated, but it might be worth thinking about doing more than chomp in your foreach loop - such as dealing with leading/trailing whitespaces and capitalization. Consider the the following quoted strings and if they all should be counted under the same key in your hash:

    • " apple"
    • "apple "
    • "APPLE"
    • "Apple"
    • "  APPle    "
    If you trust that the input file won't have such variations, then it might not cause you issues if you decide to not add some code to handle those situations.

    Another thing to consider is that using %dict and $dict might lead to some confusion for yourself later. The same could happen with using $wd and $wds.

    Just sharing the thoughts that popped into my mind when looking over your code. Not saying that any of the above is necessarily "wrong", but those are the types of things that have gotten me into trouble with my code.

Re: Mysterious hash problem
by leszekdubiel (Scribe) on Oct 27, 2023 at 19:18 UTC

    Maybe you could do it simpler:

    use Path::Tiny; my %dict = map { ($_, 1) } path("d:/perl/words.short")->lines_utf8({chomp => 1}); say "got apple" if exists $dict{apple} ;