Perl has "convenient" behaviors which optimize away common cases for folks. Some of those deal with how undefined values are handled:

#!/usr/bin/perl -l use strict; my $x; print +($x eq '') ? 'Yes' : 'No';

That prints "yes", even though an undefined value is not the same as the empty string. Many times this is what you want, but not always. To get around this, the following verbose code will suffice:

#!/usr/bin/perl -l use strict; my $x; print +(defined $x && $x eq '') ? 'Yes' : 'No';

It gets much worse if you're comparing two variables:

if ( (not defined $new and not defined $old) or (defined $new and defined $old and $old eq $new) ) { ... }

Is there some way to get Perl to force a true comparison? (yes, I can wrap that in a sub or method, but I'd like a direct comparison)

Update: the following comparison is probably a bit faster but I doubt it's easier to read.

!( defined $x xor defined $y ) && $x eq $y

Cheers,
Ovid

New address of my CGI Course.


In reply to Comparing undefined values by Ovid

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.