Writing Safe Code

Using the warnings module or the -w switch

The warnings module may help you debug your program and write safer code, by sending warnings during program compilation.
However, it will not stop the program execution.

The warnings module is new in Perl version 5.6.0. If you use an older version of Perl, use the -w switch.

Unlike -w, which applies to the entire program, the scope of the warnings module is limited to the enclosing block. Also, it is possible to disable warnings in the middle of a block by the command no warnings;

To read more about warnings, look at the perllexwarn and perldiag manual pages. e.g. on a unix command line type: man perllexwarn.

Example 1a - using the warnings module

#!/usr/local/bin/perl

use warnings;

my $a = 4;
my $b = 5;
my $c;

my $sum = $a + $b + $c;   #we used $c in an operation,
                          #though it was not initialized

print "sum: $sum\n";

# Program output:

# Use of uninitialized value in addition (+) at w1.pl line 9.
# sum: 9

Example 1b - using the 'old' -w switch

#!/usr/local/bin/perl    -w

my $a = 4;
my $b = 5;
my $c;

my $sum = $a + $b + $c;   #we used $c in an operation,
                          #though it was not initialized

print "sum: $sum\n";

# Program output:

# Use of uninitialized value in addition (+) at ./w1.pl line 7.
# sum: 9

Example 2

#!/usr/local/bin/perl

use warnings;

my $a = 5;
my $b = "John";

my $sum = $a + $b;   #we used a string ($b)
                     #inside a numeric operation

print "sum: $sum\n";

# Program output:

# Argument "John" isn't numeric in addition (+) at ./w2.pl line 8.
# sum: 5

Example 3

#!/usr/local/bin/perl

use warnings;

my $number1 = 4;
my $number2 = 5;

$number1 = $number1 * 10;
$namber2 = $number2 * 10;     #spelling mistake

print "numbers: $number1, $number2\n";

# Program output:

# Name "main::namber2" used only once: possible typo at ./w3.pl line 9.
# numbers: 40, 5

Table of Contents.
Next.