What is truth?

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;

Remember, 0, '0', '', and undef all evaluate to Perl’s notion of false.

Creative Commons License
What is truth? by Galen Charlton, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

3 thoughts on “What is truth?

  1. Galen Charlton Post author

    @chromatic
    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.

  2. Pingback: Tutorial: Perl 5.10 and Koha | Meta Interchange

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">