I think your code should work correctly - in both versions. The only difference is that you get once a warning (which is exactly that, it's not an error) and iirc these early examples in merlyn's book (I suspect you are reading the llama) don't run under -w and strict because he hasn't introduced all the concepts yet.

In if ($words{$name} eq "") the key $name is looked up in the hash %words. This returns undef when the key $name does not exist in %words. The undef is then compared to "" with a string compare, so the undef is transformed into the empty string. This results in the comparision being true. But this might be a source of error, so perl warns you if you have warnings enabled (-w).

Why might that be a source of error? Well, imagine the empty string would be a valid entry in your hash, then you get the same result no matter if the key does not exist or the value is empty. Some code:

#/usr/bin/perl -w use strict; my %hash; $hash{key1} = ""; # this produces no warning if ($hash{key1} eq "") { # true print "key1 empty!\n"; } # this produces a warning if ($hash{key2} eq "") { # true print "key2 empty!\n"; }
to circumvent this look at defined (like suggested by busunsl) and for hashes also interesting exists.

-- Hofmator


In reply to Re: Re: Re: Uninitialized value ? by Hofmator
in thread Uninitialized value ? by All0uette

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.