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

cri*_*riz 3 perl

是否可以在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";
Run Code Online (Sandbox Code Playgroud)

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

ike*_*ami 11

use strict;
Run Code Online (Sandbox Code Playgroud)

相当于

BEGIN {
   require strict;
   import strict;
}
Run Code Online (Sandbox Code Playgroud)

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

此外,两者的效果use strict和use 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';
Run Code Online (Sandbox Code Playgroud)