Why does Perl think -1 is true?
This is a piece of common 开发者_高级运维example code:
while (1) {
print "foo\n";
}
which prints 'foo' forever.
perl foo.pl
foo
foo
foo
...
and
while (0) { print "foo\n"; }
dies quietly as you expect:
perl test.pl
Can someone explain why this is a useful implementation of while? This works on 5.10 at least, Unix and MacOS X:
while (-1) { print "foo\n"; }
which gives
foo
foo
foo
...
Every non-zero integer evaluates to true
. And 0 is always false
If anything, one could say -1
is more likely to be true than 1
since -1
(111..111b
) is the bitwise negation of zero (000..000b
). BASIC and GW-BASIC used -1 when they needed to return a true value.
Regardless, Perl decided that values that mean "empty" or "nothing" are false. Most languages take a similar view. Specifically, integer zero, floating point zero, the string zero, the empty string and undef are false.
This is documented, although the documentation is poorly worded. (It lists ()
as a value that's false, but there is no such value.)
Aside from consistency, it's very useful to take this approach. For example, it allows one to use
if (@x)
instead of
if (@x != 0)
From perldoc perlsyn (Truth and Falsehood):
The number 0, the strings '0' and '' , the empty list () , and undef are all false in a boolean context. All other values are true.
-1
is considered true.
The question is 'why does perl think -1 is true?'.
The answer is when perl was developed it was decided that certain values would evaluate to false. These are:
- 0
- undef
- '' (empty string)
That is all I can think of a a suitable answer as to why. It was just designed that way.
Only a 0 integer is considered false. Any other non-zero integer is considered true.
any integer <> 0 is true. 0 is always false.
Perl took this behavior from awk
and C
.
Why C
does it is explained here.
精彩评论