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:
0
'0'
undef
'' # Empty scalar
() # Empty list
('')
The rest are true. There are no barewords for true
or false
.
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
my $boolean = 0;
if ( $boolean ) {
print "$boolean evaluates to true\n";
} else {
print "$boolean evaluates to false\n";
}
One thing that I've done in some of my programs is added the same behavior using a constant:
#!/usr/bin/perl
use strict;
use warnings;
use constant false => 0;
use constant true => 1;
my $val1 = true;
my $val2 = false;
print $val1, " && ", $val2;
if ( $val1 && $val2 ) {
print " evaluates to true.\n";
} else {
print " evaluates to false.\n";
}
print $val1, " || ", $val2;
if ( $val1 || $val2 ) {
print " evaluates to true.\n";
} else {
print " evaluates to false.\n";
}
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:
true = 0;
true = false;
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:
my $var1 = "5.0";
my $var2 = "5";
print "using operator eq\n";
if ( $var1 eq $var2 ) {
print "$var1 and $var2 are equal!\n";
} else {
print "$var1 and $var2 are not equal!\n";
}
print "using operator ==\n";
if ( $var1 == $var2 ) {
print "$var1 and $var2 are equal!\n";
} else {
print "$var1 and $var2 are not equal!\n";
}
The difference between these operators is a very common source of confusion in Perl.
I recommend use boolean;
. You have to install the boolean module from cpan though.