【问题标题】:Why does Perl complain "Useless use of a constant in void context", but only sometimes?为什么 Perl 会抱怨“在无效上下文中无用地使用常量”,但只是有时?
【发布时间】:2013-07-31 21:36:53
【问题描述】:

这是我的 Perl 脚本及其输出:

use strict;
use warnings;

(undef, 1); # no output
(0, 1);     # no output
(1, 1);     # no output
(2, 1);     # "Useless use of a constant in void context at C:\...\void.pl line 7"
(3, 1);     # "Useless use of a constant in void context at C:\...\void.pl line 8"
("", 1);    # "Useless use of a constant in void context at C:\...\void.pl line 9"
("0", 1);   # "Useless use of a constant in void context at C:\...\void.pl line 10"
("1", 1);   # "Useless use of a constant in void context at C:\...\void.pl line 11"

我希望每一行都有警告。 undef01 有什么特别之处导致这种情况不会发生?

【问题讨论】:

    标签: perl constants void


    【解决方案1】:

    记录在perldoc perldiag 中,并附有理由:

    对于等于 01 的数字常量,不会发出此警告,因为它们经常用于类似的语句中

    1 while sub_with_side_effects();
    

    至于undef,它是一个即使在无效上下文中也可以使用的函数。例如undef($x) 做的事情与 $x = undef(); 相似但不同。 (您通常需要后者。)在 void 上下文中使用不带 args 的 undef 可能会发出警告,但它需要专门的代码,而且根本不需要。

    【讨论】:

    • 我也正要说这个。它在Useless use of %s in void context 下说This warning will not be issued for numerical constants equal to 0 or 1 perldoc.perl.org/…
    • 很好地挖掘文档。不过,没有解释(undef, 1)。 (扔掉undef算不算扔掉任何东西?)
    • @Ted Hopp,我为undef 添加了解释。
    • @ikegami - 很好的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2022-12-17
    • 2020-05-12
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多