Not paying close attention to Perl’s definition of truth can sometimes lead to subtle bugs. Consider a simple scalar
$x that should contain a string exactly one character wide. If the original value of
$x can be undefined and you want to make sure it has a default value of a single space, do not do the following:
$x ||= ' ';
Why not? If
$x starts off as ‘0’, a permitted value, this line will change it to
' '. Instead, do this
$x = ' ' unless defined $x;
undef all evaluate to Perl’s notion of false.
What is truth? by Galen Charlton is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
3 thoughts on “What is truth?”
You can use the defined-or operator in Perl 5.10 instead: $x //= ‘ ‘;
Thanks, I didn’t know that. Alas, the main Perl project I work on has to remain compatible with 5.8 for a while, at least.
Comments are closed.