Commit | Line | Data |
---|---|---|
a0d0e21e LW |
1 | package Carp; |
2 | ||
f06db76b AD |
3 | =head1 NAME |
4 | ||
5 | carp - warn of errors (from perspective of caller) | |
6 | ||
7 | croak - die of errors (from perspective of caller) | |
8 | ||
9 | confess - die of errors with stack backtrace | |
10 | ||
11 | =head1 SYNOPSIS | |
12 | ||
13 | use Carp; | |
14 | croak "We're outta here!"; | |
15 | ||
16 | =head1 DESCRIPTION | |
17 | ||
18 | The Carp routines are useful in your own modules because | |
19 | they act like die() or warn(), but report where the error | |
20 | was in the code they were called from. Thus if you have a | |
21 | routine Foo() that has a carp() in it, then the carp() | |
22 | will report the error as occurring where Foo() was called, | |
23 | not where carp() was called. | |
24 | ||
25 | =cut | |
26 | ||
a0d0e21e LW |
27 | # This package implements handy routines for modules that wish to throw |
28 | # exceptions outside of the current package. | |
29 | ||
748a9306 LW |
30 | $CarpLevel = 0; # How many extra package levels to skip on carp. |
31 | ||
a0d0e21e LW |
32 | require Exporter; |
33 | @ISA = Exporter; | |
34 | @EXPORT = qw(confess croak carp); | |
35 | ||
36 | sub longmess { | |
37 | my $error = shift; | |
38 | my $mess = ""; | |
748a9306 | 39 | my $i = 1 + $CarpLevel; |
a0d0e21e LW |
40 | my ($pack,$file,$line,$sub); |
41 | while (($pack,$file,$line,$sub) = caller($i++)) { | |
42 | $mess .= "\t$sub " if $error eq "called"; | |
43 | $mess .= "$error at $file line $line\n"; | |
44 | $error = "called"; | |
45 | } | |
46 | $mess || $error; | |
47 | } | |
48 | ||
748a9306 LW |
49 | sub shortmess { # Short-circuit &longmess if called via multiple packages |
50 | my $error = $_[0]; # Instead of "shift" | |
a0d0e21e | 51 | my ($curpack) = caller(1); |
748a9306 | 52 | my $extra = $CarpLevel; |
a0d0e21e LW |
53 | my $i = 2; |
54 | my ($pack,$file,$line,$sub); | |
55 | while (($pack,$file,$line,$sub) = caller($i++)) { | |
748a9306 LW |
56 | if ($pack ne $curpack) { |
57 | if ($extra-- > 0) { | |
58 | $curpack = $pack; | |
59 | } | |
60 | else { | |
61 | return "$error at $file line $line\n"; | |
62 | } | |
63 | } | |
a0d0e21e | 64 | } |
748a9306 | 65 | goto &longmess; |
a0d0e21e LW |
66 | } |
67 | ||
68 | sub confess { die longmess @_; } | |
69 | sub croak { die shortmess @_; } | |
70 | sub carp { warn shortmess @_; } | |
71 | ||
748a9306 | 72 | 1; |