Should I turn on Perl warnings with the command-line switch or pragma?

白昼怎懂夜的黑 提交于 2019-11-29 01:28:33

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';

Do both! Always!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!