【问题标题】:Is there a built-in true/false boolean value in Perl? [duplicate]Perl 中是否有内置的真/假布尔值? [复制]
【发布时间】:2011-10-19 15:43:17
【问题描述】:

可能重复:
How do I use boolean variables in Perl?

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

我很惊讶truefalse 都通过了if...

【问题讨论】:

标签: perl


【解决方案1】:

如果你严格运行它:

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

你会明白原因:

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

它被解释为字符串"true""false",这总是正确的。 Perl 中没有定义常量,但您可以自己定义:

use constant { true => 1, false => 0 };
if(false) { print 1 }

【讨论】:

    【解决方案2】:

    您正在使用裸字 truefalse。空话是一件坏事。如果你试试这个:

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

    你可能会得到这样的东西:

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

    任何看起来不像 0 的定义值都被认为是“真”。任何未定义的值或任何看起来像 0 的值(例如 0"0")都被视为“假”。这些值没有内置关键字。您可以使用01(如果真的打扰您,请坚持使用use constant { true => 1, false => 0};。:)

    【讨论】:

    • 我正在将 4GL 代码移植到 Perl 5,并且使用常量会有所帮助。我已经忘记了那些。谢谢。
    【解决方案3】:

    始终使用警告,尤其是单行字。

    Perl 没有正确或错误的命名常量,并且在没有警告或严格启用的情况下,“裸字”(可以是常量或函数但不是的东西)被默默地解释为字符串。所以你在做if("true")if("false"),除了"""0"之外的所有字符串都是真的。

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 2013-12-09
      • 2013-07-02
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2019-01-25
      相关资源
      最近更新 更多