|P is for Practical|
Surprising result when using undefby davebaker (Pilgrim)
|on Feb 22, 2021 at 20:39 UTC||Need Help??|
davebaker has asked for the wisdom of the Perl Monks concerning the following question:
I was surprised at this result when I tried to write a couple of lines of code that would prevent an email from going out to an active mailing list, unless I (as the developer) had expressly set "is_dev_mode" to be 0 or 1 in an anonymous hash supplied as the parameter. Without expressly telling the subroutine whether or not we're in development mode, I figured, the subroutine needed to assume that we are, so as not to actually send an email to all of my important customers. So:
So I run the code, and... did all my important customers just get an embarrassing test email?
They sure did. Now, let's add "use strict;" and "use warnings;" and try it again, and throw in a warn statement to try to figure out what's happened.
Thanks for the warning, but the customers just got ANOTHER email blast.
OK, I see how $is_dev_mode was undef, and hence the warning. But if $is_dev_mode is undef, then $is_dev_mode is not equal to zero, right? And if $is_dev_mode is undef, then $is_dev_mode is not equal to 1, right? And if neither is true, then the "unless it's true" clause means $is_dev_mode gets 1 as its value (so as to avoid the embarrassing blast to all my important customers), right? Nope! is_dev_mode is still undefined.
An interesting and surprising result to me. I don't think I'll be setting variables to undef and using them in this kind of boolean test again.
I would not have thought that "( $an_undefined_variable == 0 )" would evaluate to true because, golly, undef isn't a number and so the "==" operator is testing whether one number is the same as another number. Now, in hindsight of course, it's apparent that the "==" operator is going to convert both sides to a number in order to chug along and do the best it can, and 0 seems to be the closest thing to a number for undef. I think.