Reputation: 273
Is it possible to enable/disable use strict / warnings based on ARGV in perl?
I tried this code but it doesn't work. I believe it should generate a warning error at line where '$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";
The purpose is to enable warning messages only in development.
Upvotes: 4
Views: 762
Reputation: 385657
use strict;
is equivalent to
BEGIN {
require strict;
import strict;
}
so the effect of use strict;
are unconditional (since import strict;
is evaluated before the if
is evaluated).
Furthermore, the effects of both use strict
and use warnings
are lexically-scoped, so their effects are limited to the curlies in which they are located as always.
Use
BEGIN {
if ( $ARGV[0] =~ =~ /^Y\z/i ) {
require strict;
import strict;
require warnings;
import warnings;
}
}
or
use if scalar( $ARGV[0] =~ /^Y\z/i ), 'strict';
use if scalar( $ARGV[0] =~ /^Y\z/i ), 'warnings';
Upvotes: 12
Reputation: 93636
use strict
and use warnings
are lexical. They only apply to the block that they're in. If you had put the $x = 2
in the same block as your use
statements, it would throw an exception.
Upvotes: 0