Reputation: 1779
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
...
Upvotes: 12
Views: 957
Reputation: 8591
Perl took this behavior from awk
and C
.
Why C
does it is explained here.
Upvotes: 2
Reputation: 16245
Only a 0 integer is considered false. Any other non-zero integer is considered true.
Upvotes: 3
Reputation: 385645
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)
Upvotes: 18
Reputation: 2700
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:
That is all I can think of a a suitable answer as to why. It was just designed that way.
Upvotes: 5
Reputation: 62037
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.
Upvotes: 16