2012-03-14

What's true and false in Perl and Python

Perm URL with updates: http://xahlee.org/perl-python/true_false.html

Python

The following evaluates to false:

  • False. A builtin Boolean type.
  • None. A builtin type.
  • 0. Zero.
  • 0.0. Zero, float.
  • "". Empty string.
  • []. Empty list.
  • (). Empty tuple.
  • {}. Empty dictionary.
  • {}. Empty dictionary.
  • set([]). Empty set.
  • frozenset([]). Empty frozen set.
# -*- coding: utf-8 -*-
# python

my_thing = []

if my_thing:
    print "yes"
else:
    print "no"

Perl

Perl does not have a boolean type. Basically, anything that eval to {0, undef, empty string, empty array, empty hash}, are false. Everything else is true.

Perl does automatic conversion between numbers and string, so '0' is false 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 contex, and is not very intuitive.

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

# perl
use strict;
# all false

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"}
if (undef) { print "yes\n"} else { print "no\n"}
# perl
use strict;
# empty array is false

my @myArray = ();
if (@myArray) { print "yes\n"} else { print "no\n"} # prints no
# perl
use strict;
# empty hash is false

my %myHash = ();
if (%myHash) { print "yes\n"} else { print "no\n"} # prints no
# perl
use strict;
# all true

if (1) { 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"}

Explicit Testing

# perl
use strict;
# examples of explicit testing

my $x = 5;
my $y;
if (defined($x)) { print "yes\n"} else { print "no\n"} # prints yes
if (defined($y)) { print "yes\n"} else { print "no\n"} # prints no
if ($x == 0) { print "yes\n"} else { print "no\n"} # prints no
# perl
use strict;
# testing array length

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