What if get two paired variables, and want to check that both are initialized, or both are empty or null strings?

If '0' isn't a valid value

if( ! $one == ! $two ) {

If '0' is a valid value but '' is not

if( ! length $one == ! length $two ) {

If '' is also a valid value

if( defined $one == defined $two ) {

That middle case isn't sufficient on rather old versions of Perl because it used to be that length(undef) was '0' with a warning. Now length(undef) is undef so you'll only get the warning if you treat the length as a number.

Some people replace '!' with '!!' because they use '!!' as an idiom for "I just care about whether it is true or not" or "convert to Boolean".

[ Update: I've seen people use something like

unless( $one xor $two ) {

But I find it way too easy to end up making mistakes when you start using the ultra-low-precendence Boolean operators for things other than flow control (I've found quite a few such mistakes made by some of the most experienced Perl programmers I've worked with), so I don't really like that approach. (I also don't like 'unless' but I won't go into that here.) ]

- tye        


In reply to Re^3: Do people find warning for undef with string compare useful? (bool length) by tye
in thread Do people find warning for undef with string compare useful? by perl-diddler

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.