use strict
- The use strict statement is called pragma and it is placed at the beginning of the script.
- Use strict makes sure all the variables you use will be declared with my.
- If you reference a variable that was not declared with my, it will generate an error.
- Using use strict is in most cases a good idea, because it minimizes the number of errors because of typos.
- 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.
Output:
Hello!
use warningsGlobal 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;
|
Hello!
- This is another pragma, together they are placed at the beginning of the script.
- Use warnings causes the interpreter to emit many warnings to the command window in case you're doing wrong things.
- 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.
- Use warnings will only provide warnings and continue execution i.e. wont abort the execution.
- Just type use warnings; at the beginning of your program
1 2 3 | #!/usr/local/bin/perl use strict; use warnings; |
This comment has been removed by a blog administrator.
ReplyDelete