Perl Use Strict and Use Warnings

use strict
  1. The use strict statement is called pragma and it is placed at the beginning of the script.
  2. Use strict makes sure all the variables you use will be declared with my. 
  3. If you reference a variable that was not declared with my, it will generate an error.
  4. Using use strict is in most cases a good idea, because it minimizes the number of errors because of typos. 
  5. If you don’t declare variable using my keyword then the created variable would be global, which you should avoid, reducing the scope of the variable to the place where it is needed is a good programming practice.
Example:
If you use “use strict” but don’t declare a variable.
1
2
3
4
#!/usr/local/bin/perl 
use strict;
$s = "Hello!\n";
print $s;
Output:
Global symbol "$s" requires explicit package name at st.pl line 3.
Global symbol "$s" requires explicit package name at st.pl line 4.
Execution of st.pl aborted due to compilation errors.

To avoid the error you must declare the variable using my keyword.

1
2
3
4
#!/usr/local/bin/perl 
use strict;
my $s = "Hello!\n";
print $s;
Output:
Hello!

use warnings
  1. This is another pragma, together they are placed at the beginning of the script.
  2. Use warnings causes the interpreter to emit many warnings to the command window in case you're doing wrong things.
  3. This will help you find typing mistakes in program like you missed a semicolon, you used 'elseif' and not 'elsif', you are using deprecated syntax or function, whatever like that. 
  4. Use warnings will only provide warnings and continue execution i.e. wont abort the execution.
  5. Just type use warnings; at the beginning of your program
1
2
3
#!/usr/local/bin/perl 
use strict;
use warnings;

You should always use these two pragmas in your programs as it is a good programming practice.

<-- Previous || Next -->

1 comment: