开发者

Is there a built-in true/false boolean value in Perl? [duplicate]

开发者 https://www.devze.com 2023-03-25 22:27 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How do开发者_Go百科 I use boolean variables in Perl?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do开发者_Go百科 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...


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 }


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. :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消