I have tried:
$var = false;
$var = FALSE;
$var = False;
None of these work. I get the error message
Bareword "false" not allowed while "strict subs" is in use.
I have tried:
$var = false;
$var = FALSE;
$var = False;
None of these work. I get the error message
Bareword "false" not allowed while "strict subs" is in use.
In Perl, the following evaluate to false in conditionals:
The rest are true. There are no barewords for
true
orfalse
.use the following file prefix, this will add to your perl script eTRUE and eFALSE, it will actually be REAL(!) true and false (just like java)
There are, actually, few reasons why you should use that.
My reason is that working with JSON, I've got 0 and 1 as values to keys, but this hack will make sure correct values are kept along your script.
Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide
Truth tests for different values
I recommend
use boolean;
. You have to install the boolean module from cpan though.The most complete, concise definition of false I've come across is:
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to
0
are false, strings that numify to zero aren't necessarily. The only false strings are0
and the empty string. Any other string, even if it numifies to zero, is true.The following are strings that are true as a boolean and zero as a number.
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g."abc"
)Perl doesn't have a native boolean type, but you can use comparison of integers or strings in order to get the same behavior. Alan's example is a nice way of doing that using comparison of integers. Here's an example
One thing that I've done in some of my programs is added the same behavior using a constant:
The lines marked in "use constant" define a constant named true that always evaluates to 1, and a constant named false that always evaluates by 0. Because of the way that constants are defined in Perl, the following lines of code fails as well:
The error message should say something like "Can't modify constant in scalar assignment."
I saw that in one of the comments you asked about comparing strings. You should know that because Perl combines strings and numeric types in scalar variables, you have different syntax for comparing strings and numbers:
The difference between these operators is a very common source of confusion in Perl.