Writing Safe Code

Using the diagnostics module

You may use the diagnostics module to receive detailed descriptions of your program errors. This includes both compilation and run-time errors. It is recommended to be used only during debugging phases.

The use of diagnostics also sends the -w errors, so there is no need to use both in the same program.



use diagnostics;

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

my $sum = $a + $b;   #we used a string ($b) inside a numeric operation
print "sum: $sum\n";

my $c = 0;
my $d = 5/$c;        #run-time error: illegal division by zero
print "d: $d\n";

Program output

Argument "John" isn't numeric in addition (+) at ./diag.pl line 8 (#1)

    (W numeric) The indicated string was fed as an argument to an operator that
    expected a numeric value instead.  If you're fortunate the message
    will identify which operator was so unfortunate.

sum: 5
Illegal division by zero at ./diag.pl line 12 (#2)

    (F) You tried to divide a number by 0.  Either something was wrong in your
    logic, or you need to put a conditional in to guard against meaningless input.

Uncaught exception from user code:
        Illegal division by zero at ./diag.pl line 12.

Table of Contents.