http://www.perlmonks.org?node_id=1036336


in reply to Do people find warning for undef with string compare useful?

I find it useful. IMHO you should always check for undef and never compare undef with anything. If you expect your variable to act like 0 or empty string - just assign 0 or empty string.
  • Comment on Re: Do people find warning for undef with string compare useful?

Replies are listed 'Best First'.
Re^2: Do people find warning for undef with string compare useful?
by perl-diddler (Chaplain) on Jun 01, 2013 at 14:59 UTC
    What if get two paired variables, and want to check that both are initialized, or both are empty or null strings?

    I don't necessarily want it to act like anything (0 or empty string) -- I just want it to compare as "not equal" to something that is defined, or "equal" to something that isn't -- with the caveat, that undef == undef, is only equal in a certain context -- i.e. they are both uninitialized.

    I would want it to compare different if I compared undef against 0 or the empty string, so assigning either of those other values would miss the point entirely.

      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        

      Then maybe you want 3-value-logic ?

      http://blogs.perl.org/users/ovid/2013/02/three-value-logic-in-perl.html

      http://en.wikipedia.org/wiki/Three-valued_logic

      For those very rare occasions, disable the warning locally.


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.