in reply to why can't compare a variable with undef directly?
The != operator performs a numeric comparison. Perl has built-in magic that gives scalars both numeric and string interpretations. It does the best it can at providing useful defaults when a veriable doesn't have a useful numeric equivalent.
'Hi' defaults to the number zero.
undef also defaults to zero.
When you use != against undef you are doing a numeric comparison against zero. Of your variables, only 1 is not numerically equal to zero.
You could try string comparison, eq, but that won't solve your problem either. As a string undef is equivalent to the empty string.
Using defined does exactly what you want.
Using defined also indicates that you intentionally dealing with the case where a variable might not be initialized. Uninitialized variables are an endless source of bugs. That us why you should have warnings turned on. Similarly, use strict; helps prevent a lot of other bugs.
Your program spits out warnings, if warnings are turned on
#!/usr/bin/perl use warnings; my($str,$empty_str,$number,$number_zero)=('Hi','',1,0); if($str!=undef){print"\$str is defined\n"} if($empty_str!=undef){print"\$empty_str is defined\n"} if($number!=undef){print"\$number is defined\n"} if($number_zero!=undef){print"\$number_zero is defined\n"}
Output:
Use of uninitialized value in numeric ne (!=) at ./delme.perl line 7. Argument "Hi" isn't numeric in numeric ne (!=) at ./delme.perl line 7. Use of uninitialized value in numeric ne (!=) at ./delme.perl line 8. Argument "" isn't numeric in numeric ne (!=) at ./delme.perl line 8. Use of uninitialized value in numeric ne (!=) at ./delme.perl line 9. $number is defined Use of uninitialized value in numeric ne (!=) at ./delme.perl line 10.
|
|---|