8 our $MaxArgLen = 64; # How much of each argument to print. 0 = all.
9 our $MaxArgNums = 8; # How many arguments to print. 0 = all.
12 our @ISA = ('Exporter');
13 our @EXPORT = qw(confess croak carp);
14 our @EXPORT_OK = qw(cluck verbose longmess shortmess);
15 our @EXPORT_FAIL = qw(verbose); # hook to enable verbose mode
17 # The members of %Internal are packages that are internal to perl.
18 # Carp will not report errors from within these packages if it
19 # can. The members of %CarpInternal are internal to Perl's warning
20 # system. Carp will not report errors from within these packages
21 # either, and will not report calls *to* these packages for carp and
22 # croak. They replace $CarpLevel, which is deprecated. The
23 # $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
24 # text and function arguments should be formatted when printed.
26 # disable these by default, so they can live w/o require Carp
27 $CarpInternal{Carp}++;
28 $CarpInternal{warnings}++;
29 $Internal{Exporter}++;
30 $Internal{'Exporter::Heavy'}++;
32 # if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
33 # then the following method will be called by the Exporter which knows
34 # to do this thanks to @EXPORT_FAIL, above. $_[1] will contain the word
37 sub export_fail { shift; $Verbose = shift if $_[0] eq 'verbose'; @_ }
40 # Icky backwards compatibility wrapper. :-(
42 # The story is that the original implementation hard-coded the
43 # number of call levels to go back, so calls to longmess were off
44 # by one. Other code began calling longmess and expecting this
45 # behaviour, so the replacement has to emulate that behaviour.
46 my $call_pack = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}() : caller();
47 if ($Internal{$call_pack} or $CarpInternal{$call_pack}) {
48 return longmess_heavy(@_);
51 local $CarpLevel = $CarpLevel + 1;
52 return longmess_heavy(@_);
57 # Icky backwards compatibility wrapper. :-(
58 local @CARP_NOT = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}() : caller();
62 sub croak { die shortmess @_ }
63 sub confess { die longmess @_ }
64 sub carp { warn shortmess @_ }
65 sub cluck { warn longmess @_ }
68 my $i = shift(@_) + 1;
72 @args = \$i; # A sentinal, which no-one else has the address of
74 qw(pack file line sub has_args wantarray evaltext is_require)
75 } = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}($i) : caller($i);
78 unless (defined $call_info{pack}) {
82 my $sub_name = Carp::get_subname(\%call_info);
83 if ($call_info{has_args}) {
85 if (@DB::args == 1 && ref $DB::args[0] eq ref \$i && $DB::args[0] == \$i) {
86 @DB::args = (); # Don't let anyone see the address of $i
89 my $gv = B::svref_2object(\&CORE::GLOBAL::caller)->GV;
90 my $package = $gv->STASH->NAME;
91 my $subname = $gv->NAME;
92 return unless defined $package && defined $subname;
93 # returning CORE::GLOBAL::caller isn't useful for tracing the cause:
94 return if $package eq 'CORE::GLOBAL' && $subname eq 'caller';
95 " in &${package}::$subname";
97 @args = "** Incomplete caller override detected$where; \@DB::args were not set **";
99 @args = map {Carp::format_arg($_)} @DB::args;
101 if ($MaxArgNums and @args > $MaxArgNums) { # More than we want to show?
102 $#args = $MaxArgNums;
105 # Push the args onto the subroutine
106 $sub_name .= '(' . join (', ', @args) . ')';
108 $call_info{sub_name} = $sub_name;
109 return wantarray() ? %call_info : \%call_info;
112 # Transform an argument to a function into a string.
116 $arg = defined($overload::VERSION) ? overload::StrVal($arg) : "$arg";
120 $arg = str_len_trim($arg, $MaxArgLen);
123 $arg = "'$arg'" unless $arg =~ /^-?[\d.]+\z/;
128 # The following handling of "control chars" is direct from
129 # the original code - it is broken on Unicode though.
132 or $arg =~ s/([[:cntrl:]]|[[:^ascii:]])/sprintf("\\x{%x}",ord($1))/eg;
136 # Takes an inheritance cache and a package and returns
137 # an anon hash of known inheritances and anon array of
138 # inheritances which consequences have not been figured
143 $cache->{$pkg} ||= [{$pkg => $pkg}, [trusts_directly($pkg)]];
144 return @{$cache->{$pkg}};
147 # Takes the info from caller() and figures out the name of
148 # the sub/require/eval
151 if (defined($info->{evaltext})) {
152 my $eval = $info->{evaltext};
153 if ($info->{is_require}) {
154 return "require $eval";
157 $eval =~ s/([\\\'])/\\$1/g;
158 return "eval '" . str_len_trim($eval, $MaxEvalLen) . "'";
162 return ($info->{sub} eq '(eval)') ? 'eval {...}' : $info->{sub};
165 # Figures out what call (from the point of view of the caller)
166 # the long error backtrace should start at.
169 my $lvl = $CarpLevel;
172 my $pkg = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}($i) : caller($i);
173 unless(defined($pkg)) {
174 # This *shouldn't* happen.
177 $i = long_error_loc();
181 # OK, now I am irritated.
185 redo if $CarpInternal{$pkg};
186 redo unless 0 > --$lvl;
187 redo if $Internal{$pkg};
194 return @_ if ref($_[0]); # don't break references as exceptions
195 my $i = long_error_loc();
196 return ret_backtrace($i, @_);
199 # Returns a full stack backtrace starting from where it is
202 my ($i, @error) = @_;
204 my $err = join '', @error;
208 if (defined &threads::tid) {
209 my $tid = threads->tid;
210 $tid_msg = " thread $tid" if $tid;
213 my %i = caller_info($i);
214 $mess = "$err at $i{file} line $i{line}$tid_msg\n";
216 while (my %i = caller_info(++$i)) {
217 $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
224 my ($i, @error) = @_;
225 my $err = join '', @error;
229 if (defined &threads::tid) {
230 my $tid = threads->tid;
231 $tid_msg = " thread $tid" if $tid;
234 my %i = caller_info($i);
235 return "$err at $i{file} line $i{line}$tid_msg\n";
239 sub short_error_loc {
240 # You have to create your (hash)ref out here, rather than defaulting it
241 # inside trusts *on a lexical*, as you want it to persist across calls.
242 # (You can default it on $_[2], but that gets messy)
245 my $lvl = $CarpLevel;
248 my $called = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}($i) : caller($i);
250 my $caller = defined &{"CORE::GLOBAL::caller"} ? &{"CORE::GLOBAL::caller"}($i) : caller($i);
252 return 0 unless defined($caller); # What happened?
253 redo if $Internal{$caller};
254 redo if $CarpInternal{$caller};
255 redo if $CarpInternal{$called};
256 redo if trusts($called, $caller, $cache);
257 redo if trusts($caller, $called, $cache);
258 redo unless 0 > --$lvl;
264 sub shortmess_heavy {
265 return longmess_heavy(@_) if $Verbose;
266 return @_ if ref($_[0]); # don't break references as exceptions
267 my $i = short_error_loc();
276 # If a string is too long, trims it with ...
279 my $max = shift || 0;
280 if (2 < $max and $max < length($str)) {
281 substr($str, $max - 3) = '...';
286 # Takes two packages and an optional cache. Says whether the
287 # first inherits from the second.
289 # Recursive versions of this have to work to avoid certain
290 # possible endless loops, and when following long chains of
291 # inheritance are less efficient.
296 my ($known, $partial) = get_status($cache, $child);
297 # Figure out consequences until we have an answer
298 while (@$partial and not exists $known->{$parent}) {
299 my $anc = shift @$partial;
300 next if exists $known->{$anc};
302 my ($anc_knows, $anc_partial) = get_status($cache, $anc);
303 my @found = keys %$anc_knows;
304 @$known{@found} = ();
305 push @$partial, @$anc_partial;
307 return exists $known->{$parent};
310 # Takes a package and gives a list of those trusted directly
311 sub trusts_directly {
315 return @{"$class\::CARP_NOT"}
316 ? @{"$class\::CARP_NOT"}
326 carp - warn of errors (from perspective of caller)
328 cluck - warn of errors with stack backtrace
329 (not exported by default)
331 croak - die of errors (from perspective of caller)
333 confess - die of errors with stack backtrace
338 croak "We're outta here!";
341 cluck "This is how we got here!";
345 The Carp routines are useful in your own modules because
346 they act like die() or warn(), but with a message which is more
347 likely to be useful to a user of your module. In the case of
348 cluck, confess, and longmess that context is a summary of every
349 call in the call-stack. For a shorter message you can use C<carp>
350 or C<croak> which report the error as being from where your module
351 was called. There is no guarantee that that is where the error
352 was, but it is a good educated guess.
354 You can also alter the way the output and logic of C<Carp> works, by
355 changing some global variables in the C<Carp> namespace. See the
356 section on C<GLOBAL VARIABLES> below.
358 Here is a more complete description of how C<carp> and C<croak> work.
359 What they do is search the call-stack for a function call stack where
360 they have not been told that there shouldn't be an error. If every
361 call is marked safe, they give up and give a full stack backtrace
362 instead. In other words they presume that the first likely looking
363 potential suspect is guilty. Their rules for telling whether
364 a call shouldn't generate errors work as follows:
370 Any call from a package to itself is safe.
374 Packages claim that there won't be errors on calls to or from
375 packages explicitly marked as safe by inclusion in C<@CARP_NOT>, or
376 (if that array is empty) C<@ISA>. The ability to override what
377 @ISA says is new in 5.8.
381 The trust in item 2 is transitive. If A trusts B, and B
382 trusts C, then A trusts C. So if you do not override C<@ISA>
383 with C<@CARP_NOT>, then this trust relationship is identical to,
388 Any call from an internal Perl module is safe. (Nothing keeps
389 user modules from marking themselves as internal to Perl, but
390 this practice is discouraged.)
394 Any call to Perl's warning system (eg Carp itself) is safe.
395 (This rule is what keeps it from reporting the error at the
396 point where you call C<carp> or C<croak>.)
400 C<$Carp::CarpLevel> can be set to skip a fixed number of additional
401 call levels. Using this is not recommended because it is very
402 difficult to get it to behave correctly.
406 =head2 Forcing a Stack Trace
408 As a debugging aid, you can force Carp to treat a croak as a confess
409 and a carp as a cluck across I<all> modules. In other words, force a
410 detailed stack trace to be given. This can be very helpful when trying
411 to understand why, or from where, a warning or error is being generated.
413 This feature is enabled by 'importing' the non-existent symbol
414 'verbose'. You would typically enable it by saying
416 perl -MCarp=verbose script.pl
418 or by including the string C<-MCarp=verbose> in the PERL5OPT
419 environment variable.
421 Alternately, you can set the global variable C<$Carp::Verbose> to true.
422 See the C<GLOBAL VARIABLES> section below.
424 =head1 GLOBAL VARIABLES
426 =head2 $Carp::MaxEvalLen
428 This variable determines how many characters of a string-eval are to
429 be shown in the output. Use a value of C<0> to show all text.
433 =head2 $Carp::MaxArgLen
435 This variable determines how many characters of each argument to a
436 function to print. Use a value of C<0> to show the full length of the
441 =head2 $Carp::MaxArgNums
443 This variable determines how many arguments to each function to show.
444 Use a value of C<0> to show all arguments to a function call.
448 =head2 $Carp::Verbose
450 This variable makes C<carp> and C<croak> generate stack backtraces
451 just like C<cluck> and C<confess>. This is how C<use Carp 'verbose'>
452 is implemented internally.
458 This variable, I<in your package>, says which packages are I<not> to be
459 considered as the location of an error. The C<carp()> and C<cluck()>
460 functions will skip over callers when reporting where an error occurred.
462 NB: This variable must be in the package's symbol table, thus:
465 our @CARP_NOT; # file scope
466 use vars qw(@CARP_NOT); # package scope
467 @My::Package::CARP_NOT = ... ; # explicit package variable
470 sub xyz { ... @CARP_NOT = ... } # w/o declarations above
471 my @CARP_NOT; # even at top-level
475 package My::Carping::Package;
478 sub bar { .... or _error('Wrong input') }
480 # temporary control of where'ness, __PACKAGE__ is implicit
481 local @CARP_NOT = qw(My::Friendly::Caller);
485 This would make C<Carp> report the error as coming from a caller not
486 in C<My::Carping::Package>, nor from C<My::Friendly::Caller>.
488 Also read the L</DESCRIPTION> section above, about how C<Carp> decides
489 where the error is reported from.
491 Use C<@CARP_NOT>, instead of C<$Carp::CarpLevel>.
493 Overrides C<Carp>'s use of C<@ISA>.
495 =head2 %Carp::Internal
497 This says what packages are internal to Perl. C<Carp> will never
498 report an error as being from a line in a package that is internal to
501 $Carp::Internal{ (__PACKAGE__) }++;
503 sub foo { ... or confess("whatever") };
505 would give a full stack backtrace starting from the first caller
506 outside of __PACKAGE__. (Unless that package was also internal to
509 =head2 %Carp::CarpInternal
511 This says which packages are internal to Perl's warning system. For
512 generating a full stack backtrace this is the same as being internal
513 to Perl, the stack backtrace will not start inside packages that are
514 listed in C<%Carp::CarpInternal>. But it is slightly different for
515 the summary message generated by C<carp> or C<croak>. There errors
516 will not be reported on any lines that are calling packages in
517 C<%Carp::CarpInternal>.
519 For example C<Carp> itself is listed in C<%Carp::CarpInternal>.
520 Therefore the full stack backtrace from C<confess> will not start
521 inside of C<Carp>, and the short message from calling C<croak> is
522 not placed on the line where C<croak> was called.
524 =head2 $Carp::CarpLevel
526 This variable determines how many additional call frames are to be
527 skipped that would not otherwise be when reporting where an error
528 occurred on a call to one of C<Carp>'s functions. It is fairly easy
529 to count these call frames on calls that generate a full stack
530 backtrace. However it is much harder to do this accounting for calls
531 that generate a short message. Usually people skip too many call
532 frames. If they are lucky they skip enough that C<Carp> goes all of
533 the way through the call stack, realizes that something is wrong, and
534 then generates a full stack backtrace. If they are unlucky then the
535 error is reported from somewhere misleading very high in the call
538 Therefore it is best to avoid C<$Carp::CarpLevel>. Instead use
539 C<@CARP_NOT>, C<%Carp::Internal> and C<%Carp::CarpInternal>.
545 The Carp routines don't handle exception objects currently.
546 If called with a first argument that is a reference, they simply
547 call die() or warn(), as appropriate.