Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use strict and warnings?

Tags:

perl

It seems to me that many of the questions in the Perl tag could be solved if people would use:

use strict; use warnings; 

I think some people consider these to be akin to training wheels, or unnecessary complications, which is clearly not true, since even very skilled Perl programmers use them.

It seems as though most people who are proficient in Perl always use these two pragmas, whereas those who would benefit most from using them seldom do. So, I thought it would be a good idea to have a question to link to when encouraging people to use strict and warnings.

So, why should a Perl developer use strict and warnings?

like image 655
TLP Avatar asked Nov 05 '11 23:11

TLP


People also ask

What is strict pragma?

The strict pragma checks for unsafe programming constructs. Strict forces a programmer to declare all variables as package or lexically scoped variables. Strict also forces specific syntax with sub, forcing the programmer to call each subroutine explicitly.

What is use strict in Python?

The effect of use strict "subs" is to cause a compile-time any attempt to call a function that is known not to exist. Python does not perform any such checking, and has no way to enable such a feature.

What is pragma in Perl?

In perl (as in all programming languages), a "pragma" is a directive that specifies how the compiler (or in perl's case, the interpreter) should process its input. They are not part of the language per se, but are a sort of command-line option that tells the interpreter how to behave.

What is use Perl?

In Perl, the use keyword is exactly equivalent to the following: use Mymodule; #is the same as BEGIN { require Mymodule; Mymodule->import(); } So if you are not defining an import routine in your code (or inheriting from Exporter ), then your modules are not importing anything into test.pl.


1 Answers

For starters, use strict; (and to a lesser extent, use warnings;) helps find typos in variable names. Even experienced programmers make such errors. A common case is forgetting to rename an instance of a variable when cleaning up or refactoring code.

Using use strict; use warnings; catches many errors sooner than they would be caught otherwise, which makes it easier to find the root causes of the errors. The root cause might be the need for an error or validation check, and that can happen regardless or programmer skill.

What's good about Perl warnings is that they are rarely spurious, so there's next to no cost to using them.


Related reading: Why use my?

like image 63
ikegami Avatar answered Oct 15 '22 20:10

ikegami