Perl: True, False

By Xah Lee. Date: . Last updated: .

Perl does not have a boolean type.

Anything that eval to {0, undef, empty string, empty array, empty hash}, 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, 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

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable