Perl: True, False (boolean)

By Xah Lee. Date: . Last updated: .

Perl does not have a boolean type. Basically, anything that seems should be false, is false. (of course, it can be tricky). The following are false:

Everything else is true.

Perl does automatic conversion between number and string, so '0' is false in some contexts because it converts to 0. But '0.0' is true, because it remains a string, and is not empty string.

The value of Perl's {array, list, hash}, depends on context (what's adjacent to it), and is not very intuitive.

The best thing is to test what you need exactly. For example, check if the length of a list is 0, or whether a var has value 0, or whether it is undef.

# -*- coding: utf-8 -*-
# perl

use strict;

if (0) { print "yes"} else { print "no"} # no
if (0.0) { print "yes"} else { print "no"}   # no
if ("0") { print "yes"} else { print "no"}   # no
if ("") { print "yes"} else { print "no"}  # no
if (undef) { print "yes"} else { print "no"} # no

Empty array is false:

# -*- coding: utf-8 -*-
# perl

use strict;
# empty array is false

my @myArray = ();
if (@myArray) { print "yes"} else { print "no"} #  no

Empty hash is false:

# -*- coding: utf-8 -*-
# perl

use strict;
# empty hash is false

my %myHash = ();
if (%myHash) { print "yes"} else { print "no"} #  no

Examples of some auto-conversion:

# -*- coding: utf-8 -*-
# perl

use strict;

if (1) { print "yes"} else { print "no"} #  yes
if ("0.0") { print "yes"} else { print "no"} #  yes
if (".0") { print "yes"} else { print "no"}  #  yes

Explicit Testing of Booleans

Use defined() to check if something doesn't have the value of undef.

# -*- coding: utf-8 -*-
# perl

use strict;
# examples of explicit testing

my $x = 5;
my $y;
if (defined($x)) { print "yes"} else { print "no"} #  yes
if (defined($y)) { print "yes"} else { print "no"} #  no
if ($x == 0) { print "yes"} else { print "no"} #  no
# -*- coding: utf-8 -*-
# perl

use strict;
# testing array length

my @myArray = ();
my $myArrayLength = scalar @myArray;
if ($myArrayLength == 0) { print "yes"} else { print "no"} #  yes

perldoc perldoc -f defined