Is it safe/good practice in Perl to use an empty string as false in boolean comparisons?
ex:
my $s = '';
if($s) {
print 'true';
} else {
print 'false';
}
or would the length function be a better way to go:
my $s = '';
if(length($s) > 0) {
print 'true';
} else {
print 'false';
}
When testing for true/false in an expression, you should think carefully about what you actually want to test.
If you have a string and you need to check if it has any value at all, then test for that:
if (defined $string) { ... }
If you are passing back a "boolean" value from a function, or testing the result of some internal operation, then perform a boolean check:
if ($value) { ... }
In Perl, "truth" depends on the manner in which it is evaluated. If you simply say if ($value), then the only string values that evaluate to false are the empty string '', and a literal zero '0'. (Also, any undefined value is false, so if $value has never been assigned, that would be false too.)
There are other values which may evaluate to false in a numerical context, for example 0E0, 0.0000, and the string '0 but true'. So the question "what is truth" really depends on the context, which you the programmer need to be aware of.
Internally, Perl uses '' for false and 1 for truth (for example as the result of any boolean expression such as !$value). A common technique for "canonicalizing" any value into one of these two values is !!$value -- it inverts a value twice, giving you either '' or 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With