That Q&A reference explains to the original poster how to see if a particular value is in a hash, or if a particular hash key contains a specific value.

The OP's question was, what is the proper way to check for the existance of a particular hash key, which is quite different from the answer implied in your response.

If his objective is to verify that $hash{key} has been created (and thus exists), he should use the construct that Liz provided: if (exists $hash{key} ) { ....do your stuff.... }. Again, exists will tell you if a hash key has been brought into existance, which seems to be the answer the OP was asking for.

On the other hand, if someone is interested in whether a particular key's value has been defined, one would use the defined function as in, if (defined $hash{key} ) { ....do your stuff....}

Defined differs from exists in that defined returns true if the hash's key's value has been defined, and false if the hash's key's value is undef. But it doesn't care whether or not the hash's key has been created or not. In other words, using defined, you don't know if it is returning false because the key is nonexistant, or because the value referred to by the key is undef. It makes no distinction. Defined is also applicable to other forms of scalars and function returns even.

Hope this helps.

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein


In reply to Re: Re: Best way check key availability by davido
in thread Best way check key availability by banduwgs

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.