Think about Loose Coupling | |
PerlMonks |
Use strict and warningsby runrig (Abbot) |
on Sep 08, 2001 at 04:09 UTC ( [id://111088]=perltutorial: print w/replies, xml ) | Need Help?? |
When you want to use strictWhenever your program gets over a few lines long, definitely when you can't view the whole program on one page, or sometimes when you just can't figure out what else could be wrong.Why do you want to use strict?To help you catch typos so you can quickly get on to finding more significant problems (and so we don't have to catch the typos for you either), among other reasons.Its difficult to spot '$recieve_date' when on the previous page you've been calling it '$receive_date'. Also, to give your variables as small a scope as possible so that you don't have to worry about what they're doing to other parts of your program (although that's the function of my, it forces you to use my which when properly used helps achieve this goal). Why it's not 'too much trouble' to use strictIt's just 11 extra characters at the top of your script(use strict;), and two extra characters throughout your script(my).That sounds great. How do I use strict?Put this line at the top of your script (after the shebang, e.g., '#!/usr/bin/perl' line):
Now my program's broken. What do I do?The most common error showing up looks something like this:This is the error we're going to focus on fixing. (If you are getting 'Server Error' or the like, then either check your web server error logs or run your script from the command line, or look into using CGI::Carp). Whenever you first use a variable, put 'my' in front of it, e.g.:
That seems like too much trouble. Isn't laziness a virtue?Sure we're lazy. And we don't like spending time looking for simple mistakes in your program that you could have found yourself with 'use strict'.What about warnings?Oh yeah. In version 5.6 or later you can put this right around the same place you put 'use strict;':In perl's before 5.6 (or if you just want to be portable between the versions), you can put '-w' on the 'shebang' line, or set the $^W variable (however, setting $^W will not catch compile time warnings unless its in a BEGIN{} block, so '-w' is usually preferable): If you know you want to disable warnings, you can do it in a limited scope: Or sometimes you'll have to initialize variables as in the example above that uses '$number'. See Also:Also read Ovid's excellent 'use strict' is not Perl. And (as wog pointed out): Use strict warnings and diagnostics. And Use strict warnings and diagnostics or die. And The strictures, according to Seuss. And that's it! Now you have no excuse for not using strict or warnings. And it'll make life easier for all of us :)
Back to
Tutorials
|
|