【问题标题】:Is it possible to enable/disable use strict / warnings based on ARGV in perl?是否可以在 perl 中基于 ARGV 启用/禁用使用严格/警告?
【发布时间】:2017-04-26 20:58:50
【问题描述】:

是否可以在 perl 中基于 ARGV 启用/禁用使用严格 / 警告?

我试过这段代码,但它不起作用。我相信它应该在 '$x = 2';

行产生警告错误
# Do this at the beginning of the script    
BEGIN {
        if ( $ARGV[0] =~ /^Y$/i ) {
            use strict;
            use warnings;
        }
        else {
            no strict;
            no warnings;
        }
    }

    $x = 2;

    print "x is $x\n";

目的是仅在开发中启用警告消息。

【问题讨论】:

    标签: perl


    【解决方案1】:
    use strict;
    

    等价于

    BEGIN {
       require strict;
       import strict;
    }
    

    所以use strict; 的效果是无条件的(因为在评估if 之前评估import strict;)。

    此外,use strictuse warnings 的效果都是词法范围的,因此它们的效果一如既往地仅限于它们所在的花括号。

    使用

    no strict;    # Probably not actually needed.
    no warnings;  # Probably not actually needed.
    use if scalar( $ARGV[0] =~ /^Y\z/i ), 'strict';
    use if scalar( $ARGV[0] =~ /^Y\z/i ), 'warnings';
    

    【讨论】:

    • 谢谢!如果 ARGV[0] 为 Y,我尝试了它并且工作正常,但如果 ARGV[0] 为空或不是“Y”,则会引发错误。在 /usr/opt/perl5/lib/5.8.8/if.pm 第 7 行,“使用 if”的参数太少(某些代码在列表上下文中返回空列表?)。BEGIN failed-compilation aborted at test.pl第 3 行。
    • 应该修复
    【解决方案2】:

    use strictuse warnings 是词法的。它们仅适用于它们所在的块。如果您将 $x = 2use 语句放在同一块中,则会引发异常。

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 2013-08-06
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 2010-12-12
      相关资源
      最近更新 更多