Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl think -1 is true?

Tags:

boolean

perl

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
...
like image 697
shigeta Avatar asked Oct 03 '11 16:10

shigeta


1 Answers

Every non-zero integer evaluates to true. And 0 is always false

like image 169
RiaD Avatar answered Sep 19 '22 18:09

RiaD