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
...
If anything, one could say
-1is more likely to be true than1since-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
instead of