Writing Safe Code

Enforcing the usage of my by the strict module

The strict module imposes several restrictions on your Perl program. It will send you compile-time error messages and will avoid program execution, in cases where your program does not obey the restrictions. You may choose to use strict for creating safer code and to help you debug your programs.

You may find a full description of strict in the Programming Perl book, pp. 500-501.

At this stage of the course, the relevant restriction for us is the creation of compilation errors when we use variables that were not declared with my. To achieve this, we may include the following statement on the top of our program:
use strict 'vars';

Example 1

#!/usr/local/bin/perl

# Calculate the sum of three numbers

use strict 'vars';

my $a = 8;
my $b = 9;
my $c = 10;

my $sum = $a + $b + $c;
print "sum: $sum\n";

Example 2

#!/usr/local/bin/perl

# We "forget" to declare $c with my

use strict 'vars';

my $a = 8;
my $b = 9;
   $c = 10;

my $sum = $a + $b + $c;
print "sum: $sum\n";

# This causes the following compilation error:
#
# Global symbol "$c" requires explicit package name at ./strict2.pl line 9.
# Global symbol "$c" requires explicit package name at ./strict2.pl line 11.
# Execution of ./strict2.pl aborted due to compilation errors.

Example 3

#!/usr/local/bin/perl

# We have a "spelling" mistake, and write $d
# instead of $c in the sum calculation.

use strict 'vars';

my $a = 8;
my $b = 9;
my $c = 10;

my $sum = $a + $b + $d;
print "sum: $sum\n";

# This causes the following compilation error:
#
# Global symbol "$d" requires explicit package name at ./strict3.pl line 12.
# Execution of ./strict3.pl aborted due to compilation errors.


Table of Contents.
Next.