Example: The Carp Module
This useful little module lets you do a better job of analyzing runtime errors-like when your script can't open a file or when an unexpected input value is found. It defines the carp(), croak(), and confess() fuNCtions. These are similar to warn() and die(). However, instead of reported in the exact script line where the error occurred, the fuNCtions in this module will display the line number that called the fuNCtion that generated the error. Confused? So was I, until I did some experimenting. The results of that experimenting can be found in Listing 15.6.
Load the Carp module.
Invoke the strict pragma.
Start the Foo namespace.
Define the foo() fuNCtion.
Call the carp() fuNCtion.
Call the croak() fuNCtion.
Switch to the main namespace.
Call the foo() fuNCtion.
Listing 15.6 15LST06.PL-Using the carp() and croak() from the Carp Module
use Carp;
use strict;
package Foo;
sub foo {
main::carp("carp called at line " . __LINE__ .
",\n but foo() was called");
main::croak("croak called at line " . __LINE__ .
",\n but foo() was called");
}
package main;
foo::foo();
This program displays:
carp called at line 9,
but foo() was called at e.pl line 18
croak called at line 10,
but foo() was called at e.pl line 18
This example uses a compiler symbol, __LINE__, to iNCorporate the current line number in the string passed to both carp() and croak(). This technique enables you to see both the line number where carp() and croak() were called and the line number where foo() was called.
The Carp module also defines a confess() fuNCtion which is similar to croak() except that a fuNCtion call history will also be displayed. Listing 15.7 shows how this fuNCtion can be used. The fuNCtion declarations were placed after the foo() fuNCtion call so that the program flow reads from top to bottom with no jumping around.
Load the Carp module.
Invoke the strict pragma.
Call foo().
Define foo().
Call bar().
Define bar().
Call baz().
Define baz().
Call Confess().
Listing 15.7 15LST07.PL-Using confess() from the Carp Module
use Carp;
use strict;
foo();
sub foo {
bar();
}
sub bar {
baz();
}
sub baz {
confess("I give up!");
}
This program displays:
I give up! at e.pl line 16
main::baz called at e.pl line 12
main::bar called at e.pl line 8
main::foo called at e.pl line 5
This daisy-chain of fuNCtion calls was done to show you how the fuNCtion call history looks when displayed. The fuNCtion call history is also called a stack trace. As each fuNCtion is called, the address from which it is called gets placed on a stack. When the confess() fuNCtion is called, the stack is unwound or read. This lets Perl print the fuNCtion call history.