use strict and use warnings
These two lines make Perl catch your typos and sloppy code.
In this page:
use strict and use warnings
use strict forces you to declare variables with my and stops several risky constructs, so a misspelled variable name becomes a compile-time error. use warnings prints messages about suspicious things such as using an undefined value. Almost every serious Perl script begins with both lines.
Note:
Warnings go to STDERR, so they do not mix with normal program output.
Example: use strict and use warnings
use strict;
use warnings;
my $total = 10;
my $result = eval q{ $totl + 1 }; # typo: $totl was never declared
if ($@) {
print "Caught a strict error:\n";
print $@ =~ /Global symbol "\$totl" requires explicit package name/ ? " undeclared variable \$totl\n" : " other error\n";
}
print "Total is $total\n";
# Output:
# Caught a strict error:
# undeclared variable $totl
# Total is 10
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Leaving out use strict and silently creating global variables from typos
- Ignoring warnings instead of fixing their cause
- Forgetting to declare variables with my
Chapter Summary
- use strict requires declared variables
- use warnings reports suspicious code
- Both catch typos early
- Declare variables with my
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: