As chobora points out, == is designed to compare numbers, not strings.
If the intent is to compare string values, "eq" or "ne" is the right comparison operator.

As LanX points out the right way to test for defined or not defined is with the "defined" operator.

An expression like say q() eq undef;  # 1 will indeed "work", however this will cause a warning if use warnings; is in effect: "use of unitialized value in eq".

An idiom that I use often in certain types of code is the use of the "//=" operator, like this $string //= '';.

Maybe there is something like this:

my ($keyvalue) =~ /someregex (match).../; # If the match fails, $keyvalue is going to "undefined". # Rather than test for that with some kind of "if" statement, $keyvalue //= ''; #does the job
That will assign $keyvalue to be '' (the null string) if it was "undefined".

That way I can write  if ($keyvalue eq 'important'){..} without a run-time warning if $keyvalue wasn't defined. The other place that it helps is that I can print $keyvalue without getting a different kind of warning!

What I'm saying is that sometimes it is a good idea to just convert potentially undefined strings into '', null strings and avoid any explicit conditional logic at all to ask about "defined-ness" and just use an obvious string "eq" or "ne" expression. I think the operator showed up in Perl 5.10, but that's been out there for awhile.


In reply to Re: perl undef value and eq and == by Marshall
in thread perl undef value and eq and == by freakcoco

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.