13

Possible Duplicate:
How do I use boolean variables in Perl?

[root@ ~]$ perl -e 'if(true){print 1}'
1
[root@ ~]$ perl -e 'if(false){print 1}'
1

I'm astonished both true and false passes the if...

Community
  • 1
  • 1
asker
  • 2,159
  • 3
  • 22
  • 27

3 Answers3

15

If you run it with strict:

perl -Mstrict -e 'if(true) { print 1 }'

you would get the reason:

Bareword "true" not allowed while "strict subs" in use at -e line 1.

It is interpreted as string "true" or "false" which is always true. The constants are not defined in Perl, but you can do it yourself:

use constant { true => 1, false => 0 };
if(false) { print 1 }
bvr
  • 9,687
  • 22
  • 28
10

You are using barewords true and false. Bare words are a Bad Thing. If you try this:

use strict;
use warnings;
if (true){print 1}

You'll probably get something like this:

Bareword "true" not allowed while "strict subs" in use at - line 3.
Execution of - aborted due to compilation errors.

Any defined value that doesn't look like 0 is considered "true". Any undefined value or any value that looks like 0 (such as 0 or "0") is considered "false". There's no built-in keyword for these values. You can just use 0 and 1 (or stick in use constant { true => 1, false => 0}; if it really bothers you. :)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
7

Always use warnings, especially on one-liners.

Perl has no true or false named constants, and without warnings or strict enabled, a "bareword" (something that could be a constant or function but isn't) is silently interpreted as a string. So you are doing if("true") and if("false"), and all strings other than "" or "0" are true.

ysth
  • 96,171
  • 6
  • 121
  • 214