Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 43 ยท Getting Started

use strict and use warnings

Learn why every Perl program starts with use strict and use warnings: typos, undeclared variables and bad numbers are caught early. Includes use v5.40 boilerplate.

Perl is relaxed by default. If you misspell a variable name, Perl does not complain: it quietly creates a new, empty variable and carries on. If you add a word to a number, it quietly treats the word as zero. That freedom made Perl quick to write in the early days, and it made large programs full of hidden bugs.

Two small lines fix this: use strict; and use warnings;. They are the first thing a careful Perl programmer types in every file, and they are the most important habit in this whole tutorial.

Perl does not run on this site, so Perl blocks are read-only with the real messages from Perl 5.42 shown below them. The TryIts are Python stand-ins that act out the same ideas.

What happens without them

Here is a program with a typo. The variable is $total, but the last line uses $totl:

PERL
my $total = 10;
print "Total: $totl\n";
TEXT
Total: 

Perl prints an empty value and does not complain. In a short script you might spot it. In a 500-line program, a silent mistake like this can corrupt results for weeks. Now add the two lines:

PERL
use strict;
use warnings;

my $total = 10;
print "Total: $totl\n";
TEXT
Global symbol "$totl" requires explicit package name (did you forget to declare "my $totl"?) at s2.pl line 4.
Execution of s2.pl aborted due to compilation errors.

The program stops before running anything, and the message names the exact variable and line. That is the whole value of these pragmas: mistakes become loud and early instead of silent and late.

Two pragmas, two jobs

use strict Stops risky code: undeclared variables, string references.
use warnings Reports suspicious code at run time, such as undef and bad numbers.

Strict stops the program; warnings print a message and keep going.

1 / 2

use strict

use strict; turns on three checks. You will normally see only the first two.

strict vars

Every variable must be declared before use, usually with my. This catches typos, and it also keeps variables local to their block (more in Scope, Closures and Recursion).

PERL
use strict;
use warnings;

my $x = 1;
my $x = 2;
print "$x\n";
$y = 5;
TEXT
"my" variable $x masks earlier declaration in same scope at s4.pl line 3.
Global symbol "$y" requires explicit package name (did you forget to declare "my $y"?) at s4.pl line 5.
Execution of s4.pl aborted due to compilation errors.

Two different problems appear. Declaring $x twice with my is only a warning, because it is legal. Using $y without declaring it is a compile error from strict vars. The fix is my $y = 5;.

strict refs

A string cannot be used as the name of a variable. This protects you from accidentally using a name where you meant a reference:

PERL
use strict;
use warnings;

my $r = "name";
print $$r;
TEXT
Can't use string ("name") as a SCALAR ref while "strict refs" in use at s5.pl line 3.

You will use real references in References; with strict refs, Perl makes sure you do not mix them up with strings.

strict subs

A bare word with no quotes, such as hello in my $s = hello;, is an error under strict subs rather than quietly becoming the string "hello". Always quote strings.

Python Stand-in: a typo caught early vs silently (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The lenient lookup returns nothing and carries on, which is how Perl behaves without strict. The second lookup fails loudly, which is how it behaves with strict.

use warnings

use warnings; reports suspicious things while the program runs. The program keeps going, but Perl writes a message to the error output (STDERR). The three you will meet most are:

PERL
use strict;
use warnings;

my $name;
print "Hello, $name\n";

my $n = "42abc" + 1;
print "$n\n";

my $s = "abc";
if ($s == 0) { print "equal\n"; }
TEXT
Use of uninitialized value $name in concatenation (.) or string at s3.pl line 5.
Argument "42abc" isn't numeric in addition (+) at s3.pl line 7.
Argument "abc" isn't numeric in numeric eq (==) at s3.pl line 10.
Hello, 
43
equal

The messages come out on a different stream from the normal output, so they may appear before or after the program's output in your terminal.

  • Use of uninitialized value means you used undef (the "no value" value) where a string or number was expected. It is warned about and treated as an empty string or zero.
  • isn't numeric means a string that is not entirely a number was used in arithmetic. Perl takes the leading digits (42abc becomes 42) or zero if there are none.
  • The == test is for numbers; comparing strings with it is nearly always a mistake. The right tool is eq (see Operators and Numbers).
Python Stand-in: the non-numeric string rule (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is only a Python imitation of Perl's rule, simplified. Real Perl also understands things like hexadecimal-looking strings differently and has a few special words such as Inf and NaN, but the idea is the same: take the leading number, and warn when there is more.

Declaring variables with my

Under strict, you declare a variable once, with my, the first time you use it:

PERL
use strict;
use warnings;

my $count = 0;           # declared and given a value
my ($first, $second);    # several at once, both undef
my @items = (1, 2, 3);
my %ages  = (Ada => 36);

A my variable exists only inside the block (the nearest { ... }, or the file) where it is declared. That is called lexical scope, and it keeps names from clashing across a big program.

The modern boilerplate

Typing three lines at the top of every file gets old, so modern Perl has a shortcut. Asking for a version of Perl in a use line turns on strict, warnings and other features that came with that version:

PERL
use v5.36;

This one line is the same as asking for use strict;, use warnings; and the say and signatures features. From Perl 5.40, use v5.40; also imports handy built-in functions such as true and false:

PERL
use v5.40;

my $flag = true;
say "flag=$flag";
say "off=[", false, "]";
TEXT
flag=1
off=[]

Which should you write? On a script that you control, use use v5.36; or newer (this tutorial does). When you must support older Perl, spell it out:

PERL
use strict;
use warnings;

Both work. What matters is that no file starts without one of them.

Seeing more with diagnostics

When a warning or error message is unclear, add use diagnostics; during development. It makes Perl print a longer explanation, taken from its own manual page perldiag, with each message. You can also look up any message with perldoc perldiag. Do not leave use diagnostics in production code, because it slows startup.

Habits to build now

  • Start every file with use v5.36; (or newer), or with use strict; use warnings;.
  • Declare every variable with my.
  • Read warnings as bugs to fix, not noise to hide. Do not wrap your code in no warnings; to make them go away.
  • When a message points to a line, check the line above too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you misspell a variable name under use strict?

    strict vars requires every variable to be declared, so the misspelled name is reported as a global symbol that needs an explicit package name.
  2. 2. What does use warnings do?

    Warnings, such as using an undef value or a non-numeric string in arithmetic, go to STDERR and the program keeps running.
  3. 3. Which line also enables strict, warnings and say?

    Requesting version 5.36 or newer turns on the strict and warnings pragmas and the say and signatures features.
  4. 4. What does "42abc" + 1 produce under use warnings?

    Perl uses the leading digits, so the value is 43, but warnings reports that "42abc" is not entirely numeric.

Summary

  • use strict; makes undeclared variables, string references and barewords errors, so typos fail early.
  • use warnings; reports undef values, non-numeric strings and other suspicious code without stopping the program.
  • Declare variables with my; they live only in the block where they are declared.
  • use v5.36; (or newer) turns on strict, warnings, say and signatures in one line; use v5.40; adds true and false.
  • Add use diagnostics; while learning to get longer explanations, and treat warnings as bugs to fix.

Now start storing values in Scalar Variables.