This post is about using the strict pragma.
I always use this pragma in my scripts. It helps you in keeping the script neat & clean.
As you know that by default variables are created & destroyed lexically in PERL, what I mean is by default (if you do not mention "my", "our" or "local") all variables are lexically scoped. This leads actually to errors when you mis-spell the variable names in your script.
For example:
Consider this script, of adding two numbers:
$variable1 = 10;
$variable2 = 20;
$result = $variable1 + $variable2;
This is a small script & may not have mistakes, but look at the bigger picture.
Suppose you made a mistake in the script, only just a typo:
$variable1 = 10;
$variable2 = 20;
$result = $variable1 + $varaible2;
The results are annoying. It seems like there is a logical bug (considering a bigger script), but no there is a typo. This can be caught, using the pragma strict.
Strict is pretty strict, you have to explicitly mentioned the scope of the variables when you declare them. The above script (the one with mistake) will now become:
use strict;
my $variable1 = 10;
my $variable2 = 20;
my $result = $variable1 + $varaible2;
Try running this script, you will get this error:
"Global symbol "$varaible2" requires explicit package name at test_strict.pl line 4.
Execution of test_strict.pl aborted due to compilation errors."
I think you have noticed the error by now.
Using strict pragma affects the subroutines, references & variables. You can even turnoff strict on these, for example:
no strict "vars";
For more details, goto: perldoc.perl.org/strict.html
Bottom line :-
Always 'use strict' and 'no strict' whereever necessary.
0 comments:
Post a Comment