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
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
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.
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.
"-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;" :-)
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).
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';