Alex Rivera | Logout

Why does Perl think -1 is true?

Asked 2011-10-03T16:59:28.200
12

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
...
Edit
Report

2 Answers

16

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.

answered 2011-10-03T17:03:56.187
2

any integer <> 0 is true. 0 is always false.

answered 2011-10-03T17:03:22.690

Your Answer