Learn Perl: use strict


If you're just starting with Perl, you might have fallen into a trap commonly found in online tutorials that are dated or poor quality. That trap is not enabling strict mode in your program:

$name = 'My name';
print $name;

That $variable = 'value' might seem natural to you, especially if you have some background in a language like Python. However, in Perl it is not doing what you think it does. It does not declare and assign to a local variable, but rather a global variable - a variable attached to your current package. Since there's no explicit package, that package is called main. So what the above code is really doing is:

$main::name = 'My name';
print $name;

In Perl, local variables are properly declared with the my keyword. They are called lexical to reflect their scoping rules. It is the most commonly used way to declare variables:

my $name = 'My name';
print $name;

Why didn't the interpreter warn us about the problem?

The answer is the lack of strict mode, which would prohibit such an erroneous construction. That's why almost all Perl code starts with some kind of pragma that turns it on, often together with warnings, which warn you about possible errors in your code:

use strict;
use warnings;

# this is an error now
$name = 'My name';
print $name;

Why isn't it on by default though? Other than backwards compatibility, the reason is that Perl is often used in very short, quick and dirty one line scripts, in which strict mode is undesirable, like so:

$ perl -e '$name = "My name"; print $name'

The way into the future is to declare a version of perl that you are targeting, which will automatically turn on strict mode for versions above 5.10:

use v5.32; # latest perl as of writing
use warnings;

This way you are preparing for the upcoming Perl 7, which will have a lot of modern features enabled with just a single line at the top of your file:

use v7;

Learn Perl is a series of articles targeting those who are just starting with the language. The goal is to explain some of the trickier yet commonly used parts of the syntax. See the whole series here. For a proper introduction to the language, please see the free Modern Perl book.


Comments? Suggestions? Send to feedback@brtastic.xyz
Published on 2021-05-07