views:

1037

answers:

6

Is there a difference between the two examples below for beginning a Perl script? If so, when would I use one over the other?

example 1:

#!/usr/bin/perl

use warnings;

example 2:

#!/usr/bin/perl -w
+27  A: 

Using the switch will enable all warnings in all modules used by your program. Using the pragma you enable it only in that specific module (or script). Ideally, you use warnings in all your modules, but often that's not the case. Using the switch can get you a lot of warnings when you use a third party module that isn't warnings-safe.

So, ideally it doesn't matter, but pragmatically it's often preferable for your end-users not to use the switch but the pragma.

Leon Timmermans
+16  A: 

The -w command-line switch turns on warnings globally for the entire interpreter. On the other hand, use warnings is a "lexical pragma" and only applies in the lexical scope in which it's used. Usually, you put that at the top of a file so it applies to the whole file, but you can also scope it to particular blocks. In addition, you can use no warnings to temporarily turn them off inside a block, in cases where you need to do otherwise warning-generating behavior. You can't do that if you've got -w on.

For details about how lexical warnings work, including how to turn various subsets of them on and off, see the perllexwarn document.

friedo
Your point on "no warnings" is what I expected, but a quick test (perl -w -e "no warnings; print $a;") showed that, at least on my perl, "no warnings" does still work even with -w.
Dave Sherohman
+9  A: 

"-w" is older and used to be the only way to turn warnings on (actually "-w" just enables the global $^W variable). "use warnings;" is now preferable (as of version 5.6.0 and later) because (as already mentioned) it has a lexical instead of global scope, and you can turn on/off specific warnings. And don't forget to also begin with "use strict;" :-)

runrig
As of 5.6.0. And there's warnings::compat to help if you still care about 5.5.
Schwern
Fixed. I knew I shoulda just said "5.6" :-)
runrig
But why would anyone want to use 5.6.0 anyway? :-)
runrig
A: 

Do both! Always!

JDrago
Why are you voting this down?
JDrago
+5  A: 

Another distinction worth noting, is that the "use warnings" pragma also lets you select specific warnings to enable (and likewise, "no warnings" allows you to select warnings to disable).

rjray
A: 

In addition to enabling/disabling specific assertions using the pragma, you can also promote some or all warnings to errors:

use strict;
use warnings FATAL => 'all', NONFATAL => 'exec';
That is a good idea during development, but it may not be such a good idea in deployment.
Leon Timmermans

related questions