perl false values are not printed
when I print false values in perl I get nothing printed. Probably this is a very simple question, but I searched google without finding an answer.
print "2 == 2 :", 2 == 2, "\n"; print "2 != 2 :", 2 != 2, "\n"; print "2 == 3 :", 2 == 3, "\n"; print "2 != 3 :", 2 != 3", "\n";
This is the output:
2 == 2:1 2 != 2 : 2 == 3 : 2 != 3 :1
why the false value is not being printed?
The 'false' value has been printed, sort off, don't worry about it.
Perl has a very simple concept of 'false', see the Perl Documentation for more details. The link provided by @jm666 tells more about it. Basically,
undefare all three 'false'.
You shouldn't expect to be able to print Boolean values. All that you should expect to be able to do with Boolean values is to ask them if they are true or false.
As it happens, you often can print Perl's Boolean values and get a useful result. Most Perl Boolean operations will give you 1 for true and an empty string for false. [Update: Strictly speaking, what you're getting is a dualvar with the values '' and 0.] That's what you're seeing here. The false value is being printed, but it's an empty string.
If you want to see something specific to indicate your false value, then you need to implement that yourself.
print "2 == 3 :", (2 == 3 ? 'true' : 'false'), "\n";
But really, Boolean values aren't intended for displaying.
Perl doesn't have a strict boolean type - it has a bunch of things that evaluate as 'false' and everything else is true.
Now, here's the thing - false is anything that's numerically zero, or an empty string. Or indeed
print "Zero" if 0; print "Empty" if ''; print "Undef" if undef;
None will print, because all the conditionals are 'false'.
Now, when you try and create a 'boolean' how should perl know what value to give it?
#!/usr/bin/env perl use strict; use warnings; my $value = !1; my $othervalue = !'true';
$othervalueat this point? I mean, any of
''(and a few others) would be 'valid'. But here's the thing - it doesn't matter, because it's a boolean. As long as when you feed it into
ifit does the right thing, then perl can return whatever it likes.
Perl cheats - it returns from this operation a
dualvar- a variable with two values, one for uses in a string context, and the other for use in a numeric context.
You can do a thing that doesn't work otherwise:
use Scalar::Util qw ( isdual dualvar ); print "\$value is dual\n" if isdual $value; print "Coercing numerically:", 0+$value,"\n"; print "Coercing stringifically:", ''.$value,"\n";
This won't work for normal numerical (or string) values. You can recreate the same with the
my $special = dualvar ( 666, "the beast" );
Meddling with dualvars isn't generally good practice though. Just print explicitly what you want, with a conditional test and you've got no ambiguity there.