Discussion:
boolean madness: false is the new true?
(too old to reply)
Steve Vertigan
2006-09-16 00:45:57 UTC
Permalink
I have the following method in a module I'm writing...

sub uses {
my $self = shift; my $var = shift;
if ($var) {
if ($self->{'DEFINED'}{$var}) { return true; }
else { return false; } #this line broken
} else {
my @def = keys %{$self->{'DEFINED'}};
return @def;
}
}

and using it in the context if ($obj->uses('badvar')) always tests as
true. However using return 0 instead of return false seems to
work fine. Either my perl interpreter is broken or my brain is, any
guesses?
Glenn Jackman
2006-09-16 01:23:39 UTC
Permalink
Post by Steve Vertigan
I have the following method in a module I'm writing...
sub uses {
my $self = shift; my $var = shift;
if ($var) {
if ($self->{'DEFINED'}{$var}) { return true; }
else { return false; } #this line broken
} else {
}
}
and using it in the context if ($obj->uses('badvar')) always tests as
true. However using return 0 instead of return false seems to
work fine. Either my perl interpreter is broken or my brain is, any
guesses?
Brain, I'm afraid. You're returning the unquoted string "false". Of
course, a non-empty string evaluates as a boolean true value. Using
strict and warnings would have caught it.

$ perl -le 'use strict; use warnings; sub X {return false}; print "true" if X()'
Bareword "false" not allowed while "strict subs" in use at -e line 1.
EXecution of -e aborted due to compilation errors.

$ perl -le 'use warnings; sub X {return false}; print "true" if X()'
Unquoted string "false" may clash with future reserved word at -e line 1.
true

However, you could define it as a constant:

$ perl -le '
use strict;
use warnings;
use constant false => 0;
use constant true => not false;
sub X {return false};
sub Y {return true};
print("X is: ", X() ? "true" : "false");
print("Y is: ", Y() ? "true" : "false");
'
X is: false
Y is: true
--
Glenn Jackman
Ulterior Designer
Tad McClellan
2006-09-16 04:18:18 UTC
Permalink
Post by Steve Vertigan
else { return false; } #this line broken
You should always enable warnings when developing Perl code.
--
Tad McClellan SGML consulting
***@augustmail.com Perl programming
Fort Worth, Texas
Jürgen Exner
2006-09-16 06:45:41 UTC
Permalink
Post by Steve Vertigan
I have the following method in a module I'm writing...
sub uses {
my $self = shift; my $var = shift;
if ($var) {
if ($self->{'DEFINED'}{$var}) { return true; }
else { return false; } #this line broken
} else {
}
}
and using it in the context if ($obj->uses('badvar')) always tests as
true. However using return 0 instead of return false seems to
work fine. Either my perl interpreter is broken or my brain is, any
guesses?
When trying to run your code isn't the warning message from perl quite
obvious:

Bareword "true" not allowed while "strict subs" in use at t.pl line 6.
Bareword "false" not allowed while "strict subs" in use at t.pl line 8.
Execution of t.pl aborted due to compilation errors.

jue

Loading...