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.
The following code does the following:
The Perl for this is carp.pl:
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.
The next example 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. It operates as follows:
The Perl code is carp2.pl:
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.