← Back to Perl Course | Chapter 1: Introduction | Lesson 5 of 7

use strict and use warnings

These two lines make Perl catch your typos and sloppy code.

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

perl
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
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving out use strict and silently creating global variables from typos
  2. Ignoring warnings instead of fixing their cause
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.