True and false
List of true and false values
Section titled “List of true and false values”use feature qw( say );
# Numbers are true if they're not equal to 0.say 0 ? 'true' : 'false'; # falsesay 1 ? 'true' : 'false'; # truesay 2 ? 'true' : 'false'; # truesay -1 ? 'true' : 'false'; # truesay 1-1 ? 'true' : 'false'; # falsesay 0e7 ? 'true' : 'false'; # falsesay -0.00 ? 'true' : 'false'; # false
# Strings are true if they're not empty.say 'a' ? 'true' : 'false'; # truesay 'false' ? 'true' : 'false'; # truesay '' ? 'true' : 'false'; # false
# Even if a string would be treated as 0 in numeric context, it's true if nonempty.# The only exception is the string "0", which is false.# To force numeric context add 0 to the stringsay '0' ? 'true' : 'false'; # falsesay '0.0' ? 'true' : 'false'; # truesay '0e0' ? 'true' : 'false'; # truesay '0 but true' ? 'true' : 'false'; # truesay '0 whargarbl' ? 'true' : 'false'; # truesay 0+'0 argarbl' ? 'true' : 'false'; # false
# Things that become numbers in scalar context are treated as numbers.my @c = ();my @d = (0);say @c ? 'true' : 'false'; # falsesay @d ? 'true' : 'false'; # true
# Anything undefined is false.say undef ? 'true' : 'false'; # false
# References are always true, even if they point at something falsemy @c = ();my $d = 0;say \@c ? 'true' : 'false'; # truesay \$d ? 'true' : 'false'; # truesay \0 ? 'true' : 'false'; # truesay \'' ? 'true' : 'false'; # trueSyntax
Section titled “Syntax”- undef # False
- ” # Defined, False
- 0 # Defined, Has Length, False
- ‘0’ # Defined, Has Length, False
Remarks
Section titled “Remarks”Perl does not have a boolean data type, nor does it have any true and false keywords like many other languages. However, every scalar value will evaluate to true or false when evaluated in a boolean context (the condition in an if statement or a while loop, for example).
The following values are considered false:
Section titled “The following values are considered false:”'', the empty string. This is what the built-in comparison operators return (e.g.0 == 1)0, the number 0, even if you write it as 000 or 0.0'0', the string that contains a single 0 digitundef, the undefined value- Objects that use overloading to numify/stringify into false values, such as
JSON::false
All other values are true:
Section titled “All other values are true:”- any non-zero number such as
1,3.14,'NaN'or'Inf'
If you are **intentionally** returning a true numerically 0 value, prefer `'0E0'` (used by well known modules) or `'0 but true'` (used by Perl functions)