Perl: Boolean. True, False

By Xah Lee. Date: . Last updated: .

Perl does not have a boolean type. The following are false:

False Values

Everything else is true.

use strict;

if (undef) { print "yes\n"} else { print "no\n"}

if (0) { print "yes\n"} else { print "no\n"}
if (0.0) { print "yes\n"} else { print "no\n"}

if ("0") { print "yes\n"} else { print "no\n"}

if ("") { print "yes\n"} else { print "no\n"}

# all false

# empty array is false
my @myArray = ();
if (@myArray) { print "yes\n"} else { print "no\n"}

# empty hash is false
my %myHash = ();
if (%myHash) { print "yes\n"} else { print "no\n"}

🛑 WARNING: Automatic Conversion

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. e.g. check if the length of a list is 0, or whether a var has value 0, or whether it is undef.

Examples of some auto-conversion:

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.

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
use strict;
# testing array length

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