Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 849
cowgod Avatar asked Oct 21 '08 13:10

cowgod


People also ask

What are two ways to turn on warnings in Perl?

To check if the caller's lexical scope has enabled a warning category, one can use warnings::enabled(). Another pragma warnings::warnif() can be used to produce a warning only if warnings are already in effect.

Why use strict and warnings Perl?

Strict and Warning are probably the two most commonly used Perl pragmas, and are frequently used to catch “unsafe code.” When Perl is set up to use these pragmas, the Perl compiler will check for, issue warnings against, and disallow certain programming constructs and techniques.

What is pragma in Perl?

A pragma is a module which influences some aspect of the compile time or run time behaviour of Perl, such as strict or warnings . With Perl 5.10 you are no longer limited to the built in pragmata; you can now create user pragmata that modify the behaviour of user functions within a lexical scope.

What will display a list of warning messages regarding the code in Perl?

Ans: The -w Command-line option: It will display the list if warning messages regarding the code. strict pragma: It forces the user to declare all variables before they can be used using the my() function.


2 Answers

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.

like image 198
Leon Timmermans Avatar answered Oct 15 '22 06:10

Leon Timmermans


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.

like image 33
friedo Avatar answered Oct 15 '22 06:10

friedo