Perl: True, False (boolean)
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:
- 0
undef
""
empty string- empty array
- empty hash
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. e.g. check if the length of a list is 0, or whether a var has value 0, or whether it is undef
.
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:
use strict; # empty array is false my @myArray = (); if (@myArray) { print "yes"} else { print "no"} # no
Empty hash is false:
use strict; # empty hash is false my %myHash = (); if (%myHash) { print "yes"} else { print "no"} # no
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