xref: /openbsd/gnu/usr.bin/perl/dist/Carp/lib/Carp.pm (revision e0680481)
1898184e3Ssthenpackage Carp;
2898184e3Ssthen
3898184e3Ssthen{ use 5.006; }
4898184e3Ssthenuse strict;
5898184e3Ssthenuse warnings;
6898184e3SsthenBEGIN {
76fb12b70Safresh1    # Very old versions of warnings.pm load Carp.  This can go wrong due
86fb12b70Safresh1    # to the circular dependency.  If warnings is invoked before Carp,
96fb12b70Safresh1    # then warnings starts by loading Carp, then Carp (above) tries to
106fb12b70Safresh1    # invoke warnings, and gets nothing because warnings is in the process
116fb12b70Safresh1    # of loading and hasn't defined its import method yet.  If we were
126fb12b70Safresh1    # only turning on warnings ("use warnings" above) this wouldn't be too
136fb12b70Safresh1    # bad, because Carp would just gets the state of the -w switch and so
146fb12b70Safresh1    # might not get some warnings that it wanted.  The real problem is
156fb12b70Safresh1    # that we then want to turn off Unicode warnings, but "no warnings
166fb12b70Safresh1    # 'utf8'" won't be effective if we're in this circular-dependency
176fb12b70Safresh1    # situation.  So, if warnings.pm is an affected version, we turn
186fb12b70Safresh1    # off all warnings ourselves by directly setting ${^WARNING_BITS}.
196fb12b70Safresh1    # On unaffected versions, we turn off just Unicode warnings, via
206fb12b70Safresh1    # the proper API.
216fb12b70Safresh1    if(!defined($warnings::VERSION) || eval($warnings::VERSION) < 1.06) {
226fb12b70Safresh1	${^WARNING_BITS} = "";
23898184e3Ssthen    } else {
246fb12b70Safresh1	"warnings"->unimport("utf8");
25898184e3Ssthen    }
26898184e3Ssthen}
27898184e3Ssthen
286fb12b70Safresh1sub _fetch_sub { # fetch sub without autovivifying
296fb12b70Safresh1    my($pack, $sub) = @_;
306fb12b70Safresh1    $pack .= '::';
316fb12b70Safresh1    # only works with top-level packages
326fb12b70Safresh1    return unless exists($::{$pack});
336fb12b70Safresh1    for ($::{$pack}) {
346fb12b70Safresh1	return unless ref \$_ eq 'GLOB' && *$_{HASH} && exists $$_{$sub};
356fb12b70Safresh1	for ($$_{$sub}) {
366fb12b70Safresh1	    return ref \$_ eq 'GLOB' ? *$_{CODE} : undef
376fb12b70Safresh1	}
386fb12b70Safresh1    }
396fb12b70Safresh1}
406fb12b70Safresh1
416fb12b70Safresh1# UTF8_REGEXP_PROBLEM is a compile-time constant indicating whether Carp
426fb12b70Safresh1# must avoid applying a regular expression to an upgraded (is_utf8)
436fb12b70Safresh1# string.  There are multiple problems, on different Perl versions,
446fb12b70Safresh1# that require this to be avoided.  All versions prior to 5.13.8 will
456fb12b70Safresh1# load utf8_heavy.pl for the swash system, even if the regexp doesn't
466fb12b70Safresh1# use character classes.  Perl 5.6 and Perls [5.11.2, 5.13.11) exhibit
476fb12b70Safresh1# specific problems when Carp is being invoked in the aftermath of a
486fb12b70Safresh1# syntax error.
49898184e3SsthenBEGIN {
506fb12b70Safresh1    if("$]" < 5.013011) {
516fb12b70Safresh1	*UTF8_REGEXP_PROBLEM = sub () { 1 };
526fb12b70Safresh1    } else {
536fb12b70Safresh1	*UTF8_REGEXP_PROBLEM = sub () { 0 };
546fb12b70Safresh1    }
556fb12b70Safresh1}
566fb12b70Safresh1
576fb12b70Safresh1# is_utf8() is essentially the utf8::is_utf8() function, which indicates
586fb12b70Safresh1# whether a string is represented in the upgraded form (using UTF-8
596fb12b70Safresh1# internally).  As utf8::is_utf8() is only available from Perl 5.8
606fb12b70Safresh1# onwards, extra effort is required here to make it work on Perl 5.6.
616fb12b70Safresh1BEGIN {
626fb12b70Safresh1    if(defined(my $sub = _fetch_sub utf8 => 'is_utf8')) {
636fb12b70Safresh1	*is_utf8 = $sub;
646fb12b70Safresh1    } else {
656fb12b70Safresh1	# black magic for perl 5.6
666fb12b70Safresh1	*is_utf8 = sub { unpack("C", "\xaa".$_[0]) != 170 };
676fb12b70Safresh1    }
686fb12b70Safresh1}
696fb12b70Safresh1
706fb12b70Safresh1# The downgrade() function defined here is to be used for attempts to
716fb12b70Safresh1# downgrade where it is acceptable to fail.  It must be called with a
726fb12b70Safresh1# second argument that is a true value.
736fb12b70Safresh1BEGIN {
746fb12b70Safresh1    if(defined(my $sub = _fetch_sub utf8 => 'downgrade')) {
75898184e3Ssthen	*downgrade = \&{"utf8::downgrade"};
76898184e3Ssthen    } else {
776fb12b70Safresh1	*downgrade = sub {
786fb12b70Safresh1	    my $r = "";
796fb12b70Safresh1	    my $l = length($_[0]);
806fb12b70Safresh1	    for(my $i = 0; $i != $l; $i++) {
816fb12b70Safresh1		my $o = ord(substr($_[0], $i, 1));
826fb12b70Safresh1		return if $o > 255;
836fb12b70Safresh1		$r .= chr($o);
846fb12b70Safresh1	    }
856fb12b70Safresh1	    $_[0] = $r;
866fb12b70Safresh1	};
87898184e3Ssthen    }
88898184e3Ssthen}
89898184e3Ssthen
909f11ffb7Safresh1# is_safe_printable_codepoint() indicates whether a character, specified
919f11ffb7Safresh1# by integer codepoint, is OK to output literally in a trace.  Generally
929f11ffb7Safresh1# this is if it is a printable character in the ancestral character set
939f11ffb7Safresh1# (ASCII or EBCDIC).  This is used on some Perls in situations where a
949f11ffb7Safresh1# regexp can't be used.
959f11ffb7Safresh1BEGIN {
969f11ffb7Safresh1    *is_safe_printable_codepoint =
979f11ffb7Safresh1	"$]" >= 5.007_003 ?
989f11ffb7Safresh1	    eval(q(sub ($) {
999f11ffb7Safresh1		my $u = utf8::native_to_unicode($_[0]);
1009f11ffb7Safresh1		$u >= 0x20 && $u <= 0x7e;
1019f11ffb7Safresh1	    }))
1029f11ffb7Safresh1	: ord("A") == 65 ?
1039f11ffb7Safresh1	    sub ($) { $_[0] >= 0x20 && $_[0] <= 0x7e }
1049f11ffb7Safresh1	:
1059f11ffb7Safresh1	    sub ($) {
1069f11ffb7Safresh1		# Early EBCDIC
1079f11ffb7Safresh1		# 3 EBCDIC code pages supported then;  all controls but one
1089f11ffb7Safresh1		# are the code points below SPACE.  The other one is 0x5F on
1099f11ffb7Safresh1		# POSIX-BC; FF on the other two.
1109f11ffb7Safresh1		# FIXME: there are plenty of unprintable codepoints other
1119f11ffb7Safresh1		# than those that this code and the comment above identifies
1129f11ffb7Safresh1		# as "controls".
1139f11ffb7Safresh1		$_[0] >= ord(" ") && $_[0] <= 0xff &&
1149f11ffb7Safresh1		    $_[0] != (ord ("^") == 106 ? 0x5f : 0xff);
1159f11ffb7Safresh1	    }
1169f11ffb7Safresh1	;
1179f11ffb7Safresh1}
1189f11ffb7Safresh1
1199f11ffb7Safresh1sub _univ_mod_loaded {
1209f11ffb7Safresh1    return 0 unless exists($::{"UNIVERSAL::"});
1219f11ffb7Safresh1    for ($::{"UNIVERSAL::"}) {
1229f11ffb7Safresh1	return 0 unless ref \$_ eq "GLOB" && *$_{HASH} && exists $$_{"$_[0]::"};
1239f11ffb7Safresh1	for ($$_{"$_[0]::"}) {
1249f11ffb7Safresh1	    return 0 unless ref \$_ eq "GLOB" && *$_{HASH} && exists $$_{"VERSION"};
1259f11ffb7Safresh1	    for ($$_{"VERSION"}) {
1269f11ffb7Safresh1		return 0 unless ref \$_ eq "GLOB";
1279f11ffb7Safresh1		return ${*$_{SCALAR}};
1289f11ffb7Safresh1	    }
1299f11ffb7Safresh1	}
1309f11ffb7Safresh1    }
1319f11ffb7Safresh1}
1329f11ffb7Safresh1
1339f11ffb7Safresh1# _maybe_isa() is usually the UNIVERSAL::isa function.  We have to avoid
1349f11ffb7Safresh1# the latter if the UNIVERSAL::isa module has been loaded, to avoid infi-
1359f11ffb7Safresh1# nite recursion; in that case _maybe_isa simply returns true.
1369f11ffb7Safresh1my $isa;
1379f11ffb7Safresh1BEGIN {
1389f11ffb7Safresh1    if (_univ_mod_loaded('isa')) {
1399f11ffb7Safresh1        *_maybe_isa = sub { 1 }
1409f11ffb7Safresh1    }
1419f11ffb7Safresh1    else {
1429f11ffb7Safresh1        # Since we have already done the check, record $isa for use below
1439f11ffb7Safresh1        # when defining _StrVal.
1449f11ffb7Safresh1        *_maybe_isa = $isa = _fetch_sub(UNIVERSAL => "isa");
1459f11ffb7Safresh1    }
1469f11ffb7Safresh1}
1479f11ffb7Safresh1
1489f11ffb7Safresh1
1499f11ffb7Safresh1# We need an overload::StrVal or equivalent function, but we must avoid
1509f11ffb7Safresh1# loading any modules on demand, as Carp is used from __DIE__ handlers and
1519f11ffb7Safresh1# may be invoked after a syntax error.
1529f11ffb7Safresh1# We can copy recent implementations of overload::StrVal and use
1539f11ffb7Safresh1# overloading.pm, which is the fastest implementation, so long as
1549f11ffb7Safresh1# overloading is available.  If it is not available, we use our own pure-
1559f11ffb7Safresh1# Perl StrVal.  We never actually use overload::StrVal, for various rea-
1569f11ffb7Safresh1# sons described below.
1579f11ffb7Safresh1# overload versions are as follows:
1589f11ffb7Safresh1#     undef-1.00 (up to perl 5.8.0)   uses bless (avoid!)
1599f11ffb7Safresh1#     1.01-1.17  (perl 5.8.1 to 5.14) uses Scalar::Util
1609f11ffb7Safresh1#     1.18+      (perl 5.16+)         uses overloading
1619f11ffb7Safresh1# The ancient 'bless' implementation (that inspires our pure-Perl version)
1629f11ffb7Safresh1# blesses unblessed references and must be avoided.  Those using
1639f11ffb7Safresh1# Scalar::Util use refaddr, possibly the pure-Perl implementation, which
1649f11ffb7Safresh1# has the same blessing bug, and must be avoided.  Also, Scalar::Util is
1659f11ffb7Safresh1# loaded on demand.  Since we avoid the Scalar::Util implementations, we
1669f11ffb7Safresh1# end up having to implement our own overloading.pm-based version for perl
1679f11ffb7Safresh1# 5.10.1 to 5.14.  Since it also works just as well in more recent ver-
1689f11ffb7Safresh1# sions, we use it there, too.
1699f11ffb7Safresh1BEGIN {
1709f11ffb7Safresh1    if (eval { require "overloading.pm" }) {
1719f11ffb7Safresh1        *_StrVal = eval 'sub { no overloading; "$_[0]" }'
1729f11ffb7Safresh1    }
1739f11ffb7Safresh1    else {
1749f11ffb7Safresh1        # Work around the UNIVERSAL::can/isa modules to avoid recursion.
1759f11ffb7Safresh1
1769f11ffb7Safresh1        # _mycan is either UNIVERSAL::can, or, in the presence of an
1779f11ffb7Safresh1        # override, overload::mycan.
1789f11ffb7Safresh1        *_mycan = _univ_mod_loaded('can')
1799f11ffb7Safresh1            ? do { require "overload.pm"; _fetch_sub overload => 'mycan' }
1809f11ffb7Safresh1            : \&UNIVERSAL::can;
1819f11ffb7Safresh1
182*e0680481Safresh1        # _blessed is either UNIVERSAL::isa(...), or, in the presence of an
1839f11ffb7Safresh1        # override, a hideous, but fairly reliable, workaround.
1849f11ffb7Safresh1        *_blessed = $isa
1859f11ffb7Safresh1            ? sub { &$isa($_[0], "UNIVERSAL") }
1869f11ffb7Safresh1            : sub {
1879f11ffb7Safresh1                my $probe = "UNIVERSAL::Carp_probe_" . rand;
1889f11ffb7Safresh1                no strict 'refs';
1899f11ffb7Safresh1                local *$probe = sub { "unlikely string" };
1909f11ffb7Safresh1                local $@;
1919f11ffb7Safresh1                local $SIG{__DIE__} = sub{};
1929f11ffb7Safresh1                (eval { $_[0]->$probe } || '') eq 'unlikely string'
1939f11ffb7Safresh1              };
1949f11ffb7Safresh1
1959f11ffb7Safresh1        *_StrVal = sub {
1969f11ffb7Safresh1            my $pack = ref $_[0];
1979f11ffb7Safresh1            # Perl's overload mechanism uses the presence of a special
1989f11ffb7Safresh1            # "method" named "((" or "()" to signal it is in effect.
1999f11ffb7Safresh1            # This test seeks to see if it has been set up.  "((" post-
2009f11ffb7Safresh1            # dates overloading.pm, so we can skip it.
2019f11ffb7Safresh1            return "$_[0]" unless _mycan($pack, "()");
2029f11ffb7Safresh1            # Even at this point, the invocant may not be blessed, so
2039f11ffb7Safresh1            # check for that.
2049f11ffb7Safresh1            return "$_[0]" if not _blessed($_[0]);
2059f11ffb7Safresh1            bless $_[0], "Carp";
2069f11ffb7Safresh1            my $str = "$_[0]";
2079f11ffb7Safresh1            bless $_[0], $pack;
2089f11ffb7Safresh1            $pack . substr $str, index $str, "=";
2099f11ffb7Safresh1        }
2109f11ffb7Safresh1    }
2119f11ffb7Safresh1}
2129f11ffb7Safresh1
2139f11ffb7Safresh1
214*e0680481Safresh1our $VERSION = '1.54';
215b8851fccSafresh1$VERSION =~ tr/_//d;
216898184e3Ssthen
217898184e3Ssthenour $MaxEvalLen = 0;
218898184e3Ssthenour $Verbose    = 0;
219898184e3Ssthenour $CarpLevel  = 0;
220898184e3Ssthenour $MaxArgLen  = 64;    # How much of each argument to print. 0 = all.
221898184e3Ssthenour $MaxArgNums = 8;     # How many arguments to print. 0 = all.
2226fb12b70Safresh1our $RefArgFormatter = undef; # allow caller to format reference arguments
223898184e3Ssthen
224898184e3Ssthenrequire Exporter;
225898184e3Ssthenour @ISA       = ('Exporter');
226898184e3Ssthenour @EXPORT    = qw(confess croak carp);
227898184e3Ssthenour @EXPORT_OK = qw(cluck verbose longmess shortmess);
228898184e3Ssthenour @EXPORT_FAIL = qw(verbose);    # hook to enable verbose mode
229898184e3Ssthen
230898184e3Ssthen# The members of %Internal are packages that are internal to perl.
231898184e3Ssthen# Carp will not report errors from within these packages if it
232898184e3Ssthen# can.  The members of %CarpInternal are internal to Perl's warning
233898184e3Ssthen# system.  Carp will not report errors from within these packages
234898184e3Ssthen# either, and will not report calls *to* these packages for carp and
235898184e3Ssthen# croak.  They replace $CarpLevel, which is deprecated.    The
236898184e3Ssthen# $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
237898184e3Ssthen# text and function arguments should be formatted when printed.
238898184e3Ssthen
239898184e3Ssthenour %CarpInternal;
240898184e3Ssthenour %Internal;
241898184e3Ssthen
242898184e3Ssthen# disable these by default, so they can live w/o require Carp
243898184e3Ssthen$CarpInternal{Carp}++;
244898184e3Ssthen$CarpInternal{warnings}++;
245898184e3Ssthen$Internal{Exporter}++;
246898184e3Ssthen$Internal{'Exporter::Heavy'}++;
247898184e3Ssthen
248898184e3Ssthen# if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
249898184e3Ssthen# then the following method will be called by the Exporter which knows
250898184e3Ssthen# to do this thanks to @EXPORT_FAIL, above.  $_[1] will contain the word
251898184e3Ssthen# 'verbose'.
252898184e3Ssthen
253898184e3Ssthensub export_fail { shift; $Verbose = shift if $_[0] eq 'verbose'; @_ }
254898184e3Ssthen
255898184e3Ssthensub _cgc {
256898184e3Ssthen    no strict 'refs';
257898184e3Ssthen    return \&{"CORE::GLOBAL::caller"} if defined &{"CORE::GLOBAL::caller"};
258898184e3Ssthen    return;
259898184e3Ssthen}
260898184e3Ssthen
261898184e3Ssthensub longmess {
2626fb12b70Safresh1    local($!, $^E);
263898184e3Ssthen    # Icky backwards compatibility wrapper. :-(
264898184e3Ssthen    #
265898184e3Ssthen    # The story is that the original implementation hard-coded the
266898184e3Ssthen    # number of call levels to go back, so calls to longmess were off
267898184e3Ssthen    # by one.  Other code began calling longmess and expecting this
268898184e3Ssthen    # behaviour, so the replacement has to emulate that behaviour.
269898184e3Ssthen    my $cgc = _cgc();
270898184e3Ssthen    my $call_pack = $cgc ? $cgc->() : caller();
271898184e3Ssthen    if ( $Internal{$call_pack} or $CarpInternal{$call_pack} ) {
272898184e3Ssthen        return longmess_heavy(@_);
273898184e3Ssthen    }
274898184e3Ssthen    else {
275898184e3Ssthen        local $CarpLevel = $CarpLevel + 1;
276898184e3Ssthen        return longmess_heavy(@_);
277898184e3Ssthen    }
278898184e3Ssthen}
279898184e3Ssthen
280898184e3Ssthenour @CARP_NOT;
281898184e3Ssthen
282898184e3Ssthensub shortmess {
2836fb12b70Safresh1    local($!, $^E);
284898184e3Ssthen    my $cgc = _cgc();
285898184e3Ssthen
286898184e3Ssthen    # Icky backwards compatibility wrapper. :-(
287eac174f2Safresh1    local @CARP_NOT = scalar( $cgc ? $cgc->() : caller() );
288898184e3Ssthen    shortmess_heavy(@_);
289898184e3Ssthen}
290898184e3Ssthen
291898184e3Ssthensub croak   { die shortmess @_ }
292898184e3Ssthensub confess { die longmess @_ }
293898184e3Ssthensub carp    { warn shortmess @_ }
294898184e3Ssthensub cluck   { warn longmess @_ }
295898184e3Ssthen
296898184e3SsthenBEGIN {
297898184e3Ssthen    if("$]" >= 5.015002 || ("$]" >= 5.014002 && "$]" < 5.015) ||
298898184e3Ssthen	    ("$]" >= 5.012005 && "$]" < 5.013)) {
299898184e3Ssthen	*CALLER_OVERRIDE_CHECK_OK = sub () { 1 };
300898184e3Ssthen    } else {
301898184e3Ssthen	*CALLER_OVERRIDE_CHECK_OK = sub () { 0 };
302898184e3Ssthen    }
303898184e3Ssthen}
304898184e3Ssthen
305898184e3Ssthensub caller_info {
306898184e3Ssthen    my $i = shift(@_) + 1;
307898184e3Ssthen    my %call_info;
308898184e3Ssthen    my $cgc = _cgc();
309898184e3Ssthen    {
310898184e3Ssthen	# Some things override caller() but forget to implement the
311898184e3Ssthen	# @DB::args part of it, which we need.  We check for this by
312898184e3Ssthen	# pre-populating @DB::args with a sentinel which no-one else
313898184e3Ssthen	# has the address of, so that we can detect whether @DB::args
314898184e3Ssthen	# has been properly populated.  However, on earlier versions
315898184e3Ssthen	# of perl this check tickles a bug in CORE::caller() which
316898184e3Ssthen	# leaks memory.  So we only check on fixed perls.
317898184e3Ssthen        @DB::args = \$i if CALLER_OVERRIDE_CHECK_OK;
318898184e3Ssthen        package DB;
319898184e3Ssthen        @call_info{
320898184e3Ssthen            qw(pack file line sub has_args wantarray evaltext is_require) }
321898184e3Ssthen            = $cgc ? $cgc->($i) : caller($i);
322898184e3Ssthen    }
323898184e3Ssthen
32491f110e0Safresh1    unless ( defined $call_info{file} ) {
325898184e3Ssthen        return ();
326898184e3Ssthen    }
327898184e3Ssthen
328898184e3Ssthen    my $sub_name = Carp::get_subname( \%call_info );
329898184e3Ssthen    if ( $call_info{has_args} ) {
3309f11ffb7Safresh1        # Guard our serialization of the stack from stack refcounting bugs
3319f11ffb7Safresh1        # NOTE this is NOT a complete solution, we cannot 100% guard against
3329f11ffb7Safresh1        # these bugs.  However in many cases Perl *is* capable of detecting
3339f11ffb7Safresh1        # them and throws an error when it does.  Unfortunately serializing
3349f11ffb7Safresh1        # the arguments on the stack is a perfect way of finding these bugs,
3359f11ffb7Safresh1        # even when they would not affect normal program flow that did not
3369f11ffb7Safresh1        # poke around inside the stack.  Inside of Carp.pm it makes little
3379f11ffb7Safresh1        # sense reporting these bugs, as Carp's job is to report the callers
3389f11ffb7Safresh1        # errors, not the ones it might happen to tickle while doing so.
3399f11ffb7Safresh1        # See: https://rt.perl.org/Public/Bug/Display.html?id=131046
3409f11ffb7Safresh1        # and: https://rt.perl.org/Public/Bug/Display.html?id=52610
3419f11ffb7Safresh1        # for more details and discussion. - Yves
3429f11ffb7Safresh1        my @args = map {
3439f11ffb7Safresh1                my $arg;
3449f11ffb7Safresh1                local $@= $@;
3459f11ffb7Safresh1                eval {
3469f11ffb7Safresh1                    $arg = $_;
3479f11ffb7Safresh1                    1;
3489f11ffb7Safresh1                } or do {
3499f11ffb7Safresh1                    $arg = '** argument not available anymore **';
3509f11ffb7Safresh1                };
3519f11ffb7Safresh1                $arg;
3529f11ffb7Safresh1            } @DB::args;
3539f11ffb7Safresh1        if (CALLER_OVERRIDE_CHECK_OK && @args == 1
3549f11ffb7Safresh1            && ref $args[0] eq ref \$i
3559f11ffb7Safresh1            && $args[0] == \$i ) {
3569f11ffb7Safresh1            @args = ();    # Don't let anyone see the address of $i
357898184e3Ssthen            local $@;
358898184e3Ssthen            my $where = eval {
359898184e3Ssthen                my $func    = $cgc or return '';
360898184e3Ssthen                my $gv      =
3616fb12b70Safresh1                    (_fetch_sub B => 'svref_2object' or return '')
362898184e3Ssthen                        ->($func)->GV;
363898184e3Ssthen                my $package = $gv->STASH->NAME;
364898184e3Ssthen                my $subname = $gv->NAME;
365898184e3Ssthen                return unless defined $package && defined $subname;
366898184e3Ssthen
367898184e3Ssthen                # returning CORE::GLOBAL::caller isn't useful for tracing the cause:
368898184e3Ssthen                return if $package eq 'CORE::GLOBAL' && $subname eq 'caller';
369898184e3Ssthen                " in &${package}::$subname";
370898184e3Ssthen            } || '';
371898184e3Ssthen            @args
372898184e3Ssthen                = "** Incomplete caller override detected$where; \@DB::args were not set **";
373898184e3Ssthen        }
374898184e3Ssthen        else {
37591f110e0Safresh1            my $overflow;
376898184e3Ssthen            if ( $MaxArgNums and @args > $MaxArgNums )
377898184e3Ssthen            {    # More than we want to show?
378b8851fccSafresh1                $#args = $MaxArgNums - 1;
37991f110e0Safresh1                $overflow = 1;
38091f110e0Safresh1            }
38191f110e0Safresh1
38291f110e0Safresh1            @args = map { Carp::format_arg($_) } @args;
38391f110e0Safresh1
38491f110e0Safresh1            if ($overflow) {
385898184e3Ssthen                push @args, '...';
386898184e3Ssthen            }
38791f110e0Safresh1        }
388898184e3Ssthen
389898184e3Ssthen        # Push the args onto the subroutine
390898184e3Ssthen        $sub_name .= '(' . join( ', ', @args ) . ')';
391898184e3Ssthen    }
392898184e3Ssthen    $call_info{sub_name} = $sub_name;
393898184e3Ssthen    return wantarray() ? %call_info : \%call_info;
394898184e3Ssthen}
395898184e3Ssthen
396898184e3Ssthen# Transform an argument to a function into a string.
3976fb12b70Safresh1our $in_recurse;
398898184e3Ssthensub format_arg {
399898184e3Ssthen    my $arg = shift;
4006fb12b70Safresh1
4019f11ffb7Safresh1    if ( my $pack= ref($arg) ) {
4029f11ffb7Safresh1
4036fb12b70Safresh1         # legitimate, let's not leak it.
4049f11ffb7Safresh1        if (!$in_recurse && _maybe_isa( $arg, 'UNIVERSAL' ) &&
4056fb12b70Safresh1	    do {
4066fb12b70Safresh1                local $@;
4076fb12b70Safresh1	        local $in_recurse = 1;
4086fb12b70Safresh1		local $SIG{__DIE__} = sub{};
4096fb12b70Safresh1                eval {$arg->can('CARP_TRACE') }
4106fb12b70Safresh1            })
4116fb12b70Safresh1        {
4126fb12b70Safresh1            return $arg->CARP_TRACE();
413898184e3Ssthen        }
4146fb12b70Safresh1        elsif (!$in_recurse &&
4156fb12b70Safresh1	       defined($RefArgFormatter) &&
4166fb12b70Safresh1	       do {
4176fb12b70Safresh1                local $@;
4186fb12b70Safresh1	        local $in_recurse = 1;
4196fb12b70Safresh1		local $SIG{__DIE__} = sub{};
4206fb12b70Safresh1                eval {$arg = $RefArgFormatter->($arg); 1}
4216fb12b70Safresh1                })
4226fb12b70Safresh1        {
423898184e3Ssthen            return $arg;
424898184e3Ssthen        }
4256fb12b70Safresh1        else
4266fb12b70Safresh1        {
4279f11ffb7Safresh1            # Argument may be blessed into a class with overloading, and so
4289f11ffb7Safresh1            # might have an overloaded stringification.  We don't want to
4299f11ffb7Safresh1            # risk getting the overloaded stringification, so we need to
4309f11ffb7Safresh1            # use _StrVal, our overload::StrVal()-equivalent.
4319f11ffb7Safresh1            return _StrVal $arg;
4326fb12b70Safresh1        }
4336fb12b70Safresh1    }
4346fb12b70Safresh1    return "undef" if !defined($arg);
4356fb12b70Safresh1    downgrade($arg, 1);
4366fb12b70Safresh1    return $arg if !(UTF8_REGEXP_PROBLEM && is_utf8($arg)) &&
4376fb12b70Safresh1	    $arg =~ /\A-?[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?\z/;
4386fb12b70Safresh1    my $suffix = "";
4396fb12b70Safresh1    if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
4406fb12b70Safresh1        substr ( $arg, $MaxArgLen - 3 ) = "";
4416fb12b70Safresh1	$suffix = "...";
4426fb12b70Safresh1    }
4436fb12b70Safresh1    if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
4446fb12b70Safresh1	for(my $i = length($arg); $i--; ) {
4456fb12b70Safresh1	    my $c = substr($arg, $i, 1);
4466fb12b70Safresh1	    my $x = substr($arg, 0, 0);   # work around bug on Perl 5.8.{1,2}
4476fb12b70Safresh1	    if($c eq "\"" || $c eq "\\" || $c eq "\$" || $c eq "\@") {
4486fb12b70Safresh1		substr $arg, $i, 0, "\\";
4496fb12b70Safresh1		next;
4506fb12b70Safresh1	    }
4516fb12b70Safresh1	    my $o = ord($c);
4526fb12b70Safresh1	    substr $arg, $i, 1, sprintf("\\x{%x}", $o)
4539f11ffb7Safresh1		unless is_safe_printable_codepoint($o);
4546fb12b70Safresh1	}
4556fb12b70Safresh1    } else {
4566fb12b70Safresh1	$arg =~ s/([\"\\\$\@])/\\$1/g;
457b8851fccSafresh1        # This is all the ASCII printables spelled-out.  It is portable to all
458b8851fccSafresh1        # Perl versions and platforms (such as EBCDIC).  There are other more
459b8851fccSafresh1        # compact ways to do this, but may not work everywhere every version.
4609f11ffb7Safresh1        $arg =~ s/([^ !"#\$\%\&'()*+,\-.\/0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]^_`abcdefghijklmnopqrstuvwxyz\{|}~])/sprintf("\\x{%x}",ord($1))/eg;
4616fb12b70Safresh1    }
4626fb12b70Safresh1    downgrade($arg, 1);
4636fb12b70Safresh1    return "\"".$arg."\"".$suffix;
4646fb12b70Safresh1}
4656fb12b70Safresh1
4666fb12b70Safresh1sub Regexp::CARP_TRACE {
4676fb12b70Safresh1    my $arg = "$_[0]";
4686fb12b70Safresh1    downgrade($arg, 1);
4696fb12b70Safresh1    if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
4706fb12b70Safresh1	for(my $i = length($arg); $i--; ) {
4716fb12b70Safresh1	    my $o = ord(substr($arg, $i, 1));
4726fb12b70Safresh1	    my $x = substr($arg, 0, 0);   # work around bug on Perl 5.8.{1,2}
4736fb12b70Safresh1	    substr $arg, $i, 1, sprintf("\\x{%x}", $o)
4749f11ffb7Safresh1		unless is_safe_printable_codepoint($o);
4756fb12b70Safresh1	}
4766fb12b70Safresh1    } else {
477b8851fccSafresh1        # See comment in format_arg() about this same regex.
4789f11ffb7Safresh1        $arg =~ s/([^ !"#\$\%\&'()*+,\-.\/0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]^_`abcdefghijklmnopqrstuvwxyz\{|}~])/sprintf("\\x{%x}",ord($1))/eg;
4796fb12b70Safresh1    }
4806fb12b70Safresh1    downgrade($arg, 1);
4816fb12b70Safresh1    my $suffix = "";
4826fb12b70Safresh1    if($arg =~ /\A\(\?\^?([a-z]*)(?:-[a-z]*)?:(.*)\)\z/s) {
4836fb12b70Safresh1	($suffix, $arg) = ($1, $2);
4846fb12b70Safresh1    }
4856fb12b70Safresh1    if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
4866fb12b70Safresh1        substr ( $arg, $MaxArgLen - 3 ) = "";
4876fb12b70Safresh1	$suffix = "...".$suffix;
4886fb12b70Safresh1    }
4896fb12b70Safresh1    return "qr($arg)$suffix";
4906fb12b70Safresh1}
491898184e3Ssthen
492898184e3Ssthen# Takes an inheritance cache and a package and returns
493898184e3Ssthen# an anon hash of known inheritances and anon array of
494898184e3Ssthen# inheritances which consequences have not been figured
495898184e3Ssthen# for.
496898184e3Ssthensub get_status {
497898184e3Ssthen    my $cache = shift;
498898184e3Ssthen    my $pkg   = shift;
499898184e3Ssthen    $cache->{$pkg} ||= [ { $pkg => $pkg }, [ trusts_directly($pkg) ] ];
500898184e3Ssthen    return @{ $cache->{$pkg} };
501898184e3Ssthen}
502898184e3Ssthen
503898184e3Ssthen# Takes the info from caller() and figures out the name of
504898184e3Ssthen# the sub/require/eval
505898184e3Ssthensub get_subname {
506898184e3Ssthen    my $info = shift;
507898184e3Ssthen    if ( defined( $info->{evaltext} ) ) {
508898184e3Ssthen        my $eval = $info->{evaltext};
509898184e3Ssthen        if ( $info->{is_require} ) {
510898184e3Ssthen            return "require $eval";
511898184e3Ssthen        }
512898184e3Ssthen        else {
513898184e3Ssthen            $eval =~ s/([\\\'])/\\$1/g;
514898184e3Ssthen            return "eval '" . str_len_trim( $eval, $MaxEvalLen ) . "'";
515898184e3Ssthen        }
516898184e3Ssthen    }
517898184e3Ssthen
51891f110e0Safresh1    # this can happen on older perls when the sub (or the stash containing it)
51991f110e0Safresh1    # has been deleted
52091f110e0Safresh1    if ( !defined( $info->{sub} ) ) {
52191f110e0Safresh1        return '__ANON__::__ANON__';
52291f110e0Safresh1    }
52391f110e0Safresh1
524898184e3Ssthen    return ( $info->{sub} eq '(eval)' ) ? 'eval {...}' : $info->{sub};
525898184e3Ssthen}
526898184e3Ssthen
527898184e3Ssthen# Figures out what call (from the point of view of the caller)
528898184e3Ssthen# the long error backtrace should start at.
529898184e3Ssthensub long_error_loc {
530898184e3Ssthen    my $i;
531898184e3Ssthen    my $lvl = $CarpLevel;
532898184e3Ssthen    {
533898184e3Ssthen        ++$i;
534898184e3Ssthen        my $cgc = _cgc();
53591f110e0Safresh1        my @caller = $cgc ? $cgc->($i) : caller($i);
53691f110e0Safresh1        my $pkg = $caller[0];
537898184e3Ssthen        unless ( defined($pkg) ) {
538898184e3Ssthen
539898184e3Ssthen            # This *shouldn't* happen.
540898184e3Ssthen            if (%Internal) {
541898184e3Ssthen                local %Internal;
542898184e3Ssthen                $i = long_error_loc();
543898184e3Ssthen                last;
544898184e3Ssthen            }
54591f110e0Safresh1            elsif (defined $caller[2]) {
54691f110e0Safresh1                # this can happen when the stash has been deleted
54791f110e0Safresh1                # in that case, just assume that it's a reasonable place to
54891f110e0Safresh1                # stop (the file and line data will still be intact in any
54991f110e0Safresh1                # case) - the only issue is that we can't detect if the
55091f110e0Safresh1                # deleted package was internal (so don't do that then)
55191f110e0Safresh1                # -doy
55291f110e0Safresh1                redo unless 0 > --$lvl;
55391f110e0Safresh1                last;
55491f110e0Safresh1            }
555898184e3Ssthen            else {
556898184e3Ssthen                return 2;
557898184e3Ssthen            }
558898184e3Ssthen        }
559898184e3Ssthen        redo if $CarpInternal{$pkg};
560898184e3Ssthen        redo unless 0 > --$lvl;
561898184e3Ssthen        redo if $Internal{$pkg};
562898184e3Ssthen    }
563898184e3Ssthen    return $i - 1;
564898184e3Ssthen}
565898184e3Ssthen
566898184e3Ssthensub longmess_heavy {
567b8851fccSafresh1    if ( ref( $_[0] ) ) {   # don't break references as exceptions
568b8851fccSafresh1        return wantarray ? @_ : $_[0];
569b8851fccSafresh1    }
570898184e3Ssthen    my $i = long_error_loc();
571898184e3Ssthen    return ret_backtrace( $i, @_ );
572898184e3Ssthen}
573898184e3Ssthen
5749f11ffb7Safresh1BEGIN {
5759f11ffb7Safresh1    if("$]" >= 5.017004) {
5769f11ffb7Safresh1        # The LAST_FH constant is a reference to the variable.
5779f11ffb7Safresh1        $Carp::{LAST_FH} = \eval '\${^LAST_FH}';
5789f11ffb7Safresh1    } else {
5799f11ffb7Safresh1        eval '*LAST_FH = sub () { 0 }';
5809f11ffb7Safresh1    }
5819f11ffb7Safresh1}
5829f11ffb7Safresh1
583898184e3Ssthen# Returns a full stack backtrace starting from where it is
584898184e3Ssthen# told.
585898184e3Ssthensub ret_backtrace {
586898184e3Ssthen    my ( $i, @error ) = @_;
587898184e3Ssthen    my $mess;
588898184e3Ssthen    my $err = join '', @error;
589898184e3Ssthen    $i++;
590898184e3Ssthen
591898184e3Ssthen    my $tid_msg = '';
592898184e3Ssthen    if ( defined &threads::tid ) {
593898184e3Ssthen        my $tid = threads->tid;
594898184e3Ssthen        $tid_msg = " thread $tid" if $tid;
595898184e3Ssthen    }
596898184e3Ssthen
597898184e3Ssthen    my %i = caller_info($i);
598898184e3Ssthen    $mess = "$err at $i{file} line $i{line}$tid_msg";
5999f11ffb7Safresh1    if( $. ) {
6009f11ffb7Safresh1      # Use ${^LAST_FH} if available.
6019f11ffb7Safresh1      if (LAST_FH) {
6029f11ffb7Safresh1        if (${+LAST_FH}) {
6039f11ffb7Safresh1            $mess .= sprintf ", <%s> %s %d",
6049f11ffb7Safresh1                              *${+LAST_FH}{NAME},
6059f11ffb7Safresh1                              ($/ eq "\n" ? "line" : "chunk"), $.
6069f11ffb7Safresh1        }
6079f11ffb7Safresh1      }
6089f11ffb7Safresh1      else {
609898184e3Ssthen        local $@ = '';
610898184e3Ssthen        local $SIG{__DIE__};
611898184e3Ssthen        eval {
612898184e3Ssthen            CORE::die;
613898184e3Ssthen        };
6149f11ffb7Safresh1        if($@ =~ /^Died at .*(, <.*?> (?:line|chunk) \d+).$/ ) {
615898184e3Ssthen            $mess .= $1;
616898184e3Ssthen        }
617898184e3Ssthen      }
6189f11ffb7Safresh1    }
619898184e3Ssthen    $mess .= "\.\n";
620898184e3Ssthen
621898184e3Ssthen    while ( my %i = caller_info( ++$i ) ) {
622898184e3Ssthen        $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
623898184e3Ssthen    }
624898184e3Ssthen
625898184e3Ssthen    return $mess;
626898184e3Ssthen}
627898184e3Ssthen
628898184e3Ssthensub ret_summary {
629898184e3Ssthen    my ( $i, @error ) = @_;
630898184e3Ssthen    my $err = join '', @error;
631898184e3Ssthen    $i++;
632898184e3Ssthen
633898184e3Ssthen    my $tid_msg = '';
634898184e3Ssthen    if ( defined &threads::tid ) {
635898184e3Ssthen        my $tid = threads->tid;
636898184e3Ssthen        $tid_msg = " thread $tid" if $tid;
637898184e3Ssthen    }
638898184e3Ssthen
639898184e3Ssthen    my %i = caller_info($i);
640898184e3Ssthen    return "$err at $i{file} line $i{line}$tid_msg\.\n";
641898184e3Ssthen}
642898184e3Ssthen
643898184e3Ssthensub short_error_loc {
644898184e3Ssthen    # You have to create your (hash)ref out here, rather than defaulting it
645898184e3Ssthen    # inside trusts *on a lexical*, as you want it to persist across calls.
646898184e3Ssthen    # (You can default it on $_[2], but that gets messy)
647898184e3Ssthen    my $cache = {};
648898184e3Ssthen    my $i     = 1;
649898184e3Ssthen    my $lvl   = $CarpLevel;
650898184e3Ssthen    {
651898184e3Ssthen        my $cgc = _cgc();
652898184e3Ssthen        my $called = $cgc ? $cgc->($i) : caller($i);
653898184e3Ssthen        $i++;
654898184e3Ssthen        my $caller = $cgc ? $cgc->($i) : caller($i);
655898184e3Ssthen
65691f110e0Safresh1        if (!defined($caller)) {
65791f110e0Safresh1            my @caller = $cgc ? $cgc->($i) : caller($i);
65891f110e0Safresh1            if (@caller) {
65991f110e0Safresh1                # if there's no package but there is other caller info, then
66091f110e0Safresh1                # the package has been deleted - treat this as a valid package
66191f110e0Safresh1                # in this case
66291f110e0Safresh1                redo if defined($called) && $CarpInternal{$called};
66391f110e0Safresh1                redo unless 0 > --$lvl;
66491f110e0Safresh1                last;
66591f110e0Safresh1            }
66691f110e0Safresh1            else {
66791f110e0Safresh1                return 0;
66891f110e0Safresh1            }
66991f110e0Safresh1        }
670898184e3Ssthen        redo if $Internal{$caller};
671898184e3Ssthen        redo if $CarpInternal{$caller};
672898184e3Ssthen        redo if $CarpInternal{$called};
673898184e3Ssthen        redo if trusts( $called, $caller, $cache );
674898184e3Ssthen        redo if trusts( $caller, $called, $cache );
675898184e3Ssthen        redo unless 0 > --$lvl;
676898184e3Ssthen    }
677898184e3Ssthen    return $i - 1;
678898184e3Ssthen}
679898184e3Ssthen
680898184e3Ssthensub shortmess_heavy {
681898184e3Ssthen    return longmess_heavy(@_) if $Verbose;
682898184e3Ssthen    return @_ if ref( $_[0] );    # don't break references as exceptions
683898184e3Ssthen    my $i = short_error_loc();
684898184e3Ssthen    if ($i) {
685898184e3Ssthen        ret_summary( $i, @_ );
686898184e3Ssthen    }
687898184e3Ssthen    else {
688898184e3Ssthen        longmess_heavy(@_);
689898184e3Ssthen    }
690898184e3Ssthen}
691898184e3Ssthen
692898184e3Ssthen# If a string is too long, trims it with ...
693898184e3Ssthensub str_len_trim {
694898184e3Ssthen    my $str = shift;
695898184e3Ssthen    my $max = shift || 0;
696898184e3Ssthen    if ( 2 < $max and $max < length($str) ) {
697898184e3Ssthen        substr( $str, $max - 3 ) = '...';
698898184e3Ssthen    }
699898184e3Ssthen    return $str;
700898184e3Ssthen}
701898184e3Ssthen
702898184e3Ssthen# Takes two packages and an optional cache.  Says whether the
703898184e3Ssthen# first inherits from the second.
704898184e3Ssthen#
705898184e3Ssthen# Recursive versions of this have to work to avoid certain
706898184e3Ssthen# possible endless loops, and when following long chains of
707898184e3Ssthen# inheritance are less efficient.
708898184e3Ssthensub trusts {
709898184e3Ssthen    my $child  = shift;
710898184e3Ssthen    my $parent = shift;
711898184e3Ssthen    my $cache  = shift;
712898184e3Ssthen    my ( $known, $partial ) = get_status( $cache, $child );
713898184e3Ssthen
714898184e3Ssthen    # Figure out consequences until we have an answer
715898184e3Ssthen    while ( @$partial and not exists $known->{$parent} ) {
716898184e3Ssthen        my $anc = shift @$partial;
717898184e3Ssthen        next if exists $known->{$anc};
718898184e3Ssthen        $known->{$anc}++;
719898184e3Ssthen        my ( $anc_knows, $anc_partial ) = get_status( $cache, $anc );
720898184e3Ssthen        my @found = keys %$anc_knows;
721898184e3Ssthen        @$known{@found} = ();
722898184e3Ssthen        push @$partial, @$anc_partial;
723898184e3Ssthen    }
724898184e3Ssthen    return exists $known->{$parent};
725898184e3Ssthen}
726898184e3Ssthen
727898184e3Ssthen# Takes a package and gives a list of those trusted directly
728898184e3Ssthensub trusts_directly {
729898184e3Ssthen    my $class = shift;
730898184e3Ssthen    no strict 'refs';
7316fb12b70Safresh1    my $stash = \%{"$class\::"};
7326fb12b70Safresh1    for my $var (qw/ CARP_NOT ISA /) {
7336fb12b70Safresh1        # Don't try using the variable until we know it exists,
7346fb12b70Safresh1        # to avoid polluting the caller's namespace.
7359f11ffb7Safresh1        if ( $stash->{$var} && ref \$stash->{$var} eq 'GLOB'
7369f11ffb7Safresh1          && *{$stash->{$var}}{ARRAY} && @{$stash->{$var}} ) {
7376fb12b70Safresh1           return @{$stash->{$var}}
7386fb12b70Safresh1        }
7396fb12b70Safresh1    }
7406fb12b70Safresh1    return;
741898184e3Ssthen}
742898184e3Ssthen
743898184e3Ssthenif(!defined($warnings::VERSION) ||
744898184e3Ssthen	do { no warnings "numeric"; $warnings::VERSION < 1.03 }) {
745898184e3Ssthen    # Very old versions of warnings.pm import from Carp.  This can go
746898184e3Ssthen    # wrong due to the circular dependency.  If Carp is invoked before
747898184e3Ssthen    # warnings, then Carp starts by loading warnings, then warnings
748898184e3Ssthen    # tries to import from Carp, and gets nothing because Carp is in
749898184e3Ssthen    # the process of loading and hasn't defined its import method yet.
750898184e3Ssthen    # So we work around that by manually exporting to warnings here.
751898184e3Ssthen    no strict "refs";
752898184e3Ssthen    *{"warnings::$_"} = \&$_ foreach @EXPORT;
753898184e3Ssthen}
754898184e3Ssthen
755898184e3Ssthen1;
756898184e3Ssthen
757898184e3Ssthen__END__
758898184e3Ssthen
759898184e3Ssthen=head1 NAME
760898184e3Ssthen
761898184e3SsthenCarp - alternative warn and die for modules
762898184e3Ssthen
763898184e3Ssthen=head1 SYNOPSIS
764898184e3Ssthen
765898184e3Ssthen    use Carp;
766898184e3Ssthen
767898184e3Ssthen    # warn user (from perspective of caller)
768898184e3Ssthen    carp "string trimmed to 80 chars";
769898184e3Ssthen
770898184e3Ssthen    # die of errors (from perspective of caller)
771898184e3Ssthen    croak "We're outta here!";
772898184e3Ssthen
773898184e3Ssthen    # die of errors with stack backtrace
774898184e3Ssthen    confess "not implemented";
775898184e3Ssthen
77691f110e0Safresh1    # cluck, longmess and shortmess not exported by default
77791f110e0Safresh1    use Carp qw(cluck longmess shortmess);
7789f11ffb7Safresh1    cluck "This is how we got here!"; # warn with stack backtrace
779*e0680481Safresh1    my $long_message   = longmess( "message from cluck() or confess()" );
780*e0680481Safresh1    my $short_message  = shortmess( "message from carp() or croak()" );
781898184e3Ssthen
782898184e3Ssthen=head1 DESCRIPTION
783898184e3Ssthen
784898184e3SsthenThe Carp routines are useful in your own modules because
78591f110e0Safresh1they act like C<die()> or C<warn()>, but with a message which is more
786898184e3Ssthenlikely to be useful to a user of your module.  In the case of
78791f110e0Safresh1C<cluck()> and C<confess()>, that context is a summary of every
78891f110e0Safresh1call in the call-stack; C<longmess()> returns the contents of the error
78991f110e0Safresh1message.
79091f110e0Safresh1
79191f110e0Safresh1For a shorter message you can use C<carp()> or C<croak()> which report the
79291f110e0Safresh1error as being from where your module was called.  C<shortmess()> returns the
79391f110e0Safresh1contents of this error message.  There is no guarantee that that is where the
79491f110e0Safresh1error was, but it is a good educated guess.
795898184e3Ssthen
7966fb12b70Safresh1C<Carp> takes care not to clobber the status variables C<$!> and C<$^E>
7976fb12b70Safresh1in the course of assembling its error messages.  This means that a
7986fb12b70Safresh1C<$SIG{__DIE__}> or C<$SIG{__WARN__}> handler can capture the error
7996fb12b70Safresh1information held in those variables, if it is required to augment the
8006fb12b70Safresh1error message, and if the code calling C<Carp> left useful values there.
8016fb12b70Safresh1Of course, C<Carp> can't guarantee the latter.
8026fb12b70Safresh1
803898184e3SsthenYou can also alter the way the output and logic of C<Carp> works, by
804898184e3Ssthenchanging some global variables in the C<Carp> namespace. See the
805*e0680481Safresh1section on L</GLOBAL VARIABLES> below.
806898184e3Ssthen
807898184e3SsthenHere is a more complete description of how C<carp> and C<croak> work.
808898184e3SsthenWhat they do is search the call-stack for a function call stack where
809898184e3Ssthenthey have not been told that there shouldn't be an error.  If every
810898184e3Ssthencall is marked safe, they give up and give a full stack backtrace
811898184e3Sstheninstead.  In other words they presume that the first likely looking
812898184e3Ssthenpotential suspect is guilty.  Their rules for telling whether
813898184e3Ssthena call shouldn't generate errors work as follows:
814898184e3Ssthen
815898184e3Ssthen=over 4
816898184e3Ssthen
817898184e3Ssthen=item 1.
818898184e3Ssthen
819898184e3SsthenAny call from a package to itself is safe.
820898184e3Ssthen
821898184e3Ssthen=item 2.
822898184e3Ssthen
823898184e3SsthenPackages claim that there won't be errors on calls to or from
824898184e3Ssthenpackages explicitly marked as safe by inclusion in C<@CARP_NOT>, or
825898184e3Ssthen(if that array is empty) C<@ISA>.  The ability to override what
826898184e3Ssthen@ISA says is new in 5.8.
827898184e3Ssthen
828898184e3Ssthen=item 3.
829898184e3Ssthen
830898184e3SsthenThe trust in item 2 is transitive.  If A trusts B, and B
831898184e3Ssthentrusts C, then A trusts C.  So if you do not override C<@ISA>
832898184e3Ssthenwith C<@CARP_NOT>, then this trust relationship is identical to,
833898184e3Ssthen"inherits from".
834898184e3Ssthen
835898184e3Ssthen=item 4.
836898184e3Ssthen
837898184e3SsthenAny call from an internal Perl module is safe.  (Nothing keeps
838898184e3Ssthenuser modules from marking themselves as internal to Perl, but
839898184e3Ssthenthis practice is discouraged.)
840898184e3Ssthen
841898184e3Ssthen=item 5.
842898184e3Ssthen
843898184e3SsthenAny call to Perl's warning system (eg Carp itself) is safe.
844898184e3Ssthen(This rule is what keeps it from reporting the error at the
845898184e3Ssthenpoint where you call C<carp> or C<croak>.)
846898184e3Ssthen
847898184e3Ssthen=item 6.
848898184e3Ssthen
849898184e3SsthenC<$Carp::CarpLevel> can be set to skip a fixed number of additional
850898184e3Ssthencall levels.  Using this is not recommended because it is very
851898184e3Ssthendifficult to get it to behave correctly.
852898184e3Ssthen
853898184e3Ssthen=back
854898184e3Ssthen
855898184e3Ssthen=head2 Forcing a Stack Trace
856898184e3Ssthen
857898184e3SsthenAs a debugging aid, you can force Carp to treat a croak as a confess
858898184e3Ssthenand a carp as a cluck across I<all> modules. In other words, force a
859898184e3Ssthendetailed stack trace to be given.  This can be very helpful when trying
860898184e3Ssthento understand why, or from where, a warning or error is being generated.
861898184e3Ssthen
862898184e3SsthenThis feature is enabled by 'importing' the non-existent symbol
863898184e3Ssthen'verbose'. You would typically enable it by saying
864898184e3Ssthen
865898184e3Ssthen    perl -MCarp=verbose script.pl
866898184e3Ssthen
867898184e3Ssthenor by including the string C<-MCarp=verbose> in the PERL5OPT
868898184e3Ssthenenvironment variable.
869898184e3Ssthen
870898184e3SsthenAlternately, you can set the global variable C<$Carp::Verbose> to true.
871*e0680481Safresh1See the L</GLOBAL VARIABLES> section below.
872898184e3Ssthen
8736fb12b70Safresh1=head2 Stack Trace formatting
8746fb12b70Safresh1
8756fb12b70Safresh1At each stack level, the subroutine's name is displayed along with
8766fb12b70Safresh1its parameters.  For simple scalars, this is sufficient.  For complex
8776fb12b70Safresh1data types, such as objects and other references, this can simply
8786fb12b70Safresh1display C<'HASH(0x1ab36d8)'>.
8796fb12b70Safresh1
8806fb12b70Safresh1Carp gives two ways to control this.
8816fb12b70Safresh1
8826fb12b70Safresh1=over 4
8836fb12b70Safresh1
8846fb12b70Safresh1=item 1.
8856fb12b70Safresh1
8866fb12b70Safresh1For objects, a method, C<CARP_TRACE>, will be called, if it exists.  If
8876fb12b70Safresh1this method doesn't exist, or it recurses into C<Carp>, or it otherwise
8886fb12b70Safresh1throws an exception, this is skipped, and Carp moves on to the next option,
8896fb12b70Safresh1otherwise checking stops and the string returned is used.  It is recommended
8906fb12b70Safresh1that the object's type is part of the string to make debugging easier.
8916fb12b70Safresh1
8926fb12b70Safresh1=item 2.
8936fb12b70Safresh1
8946fb12b70Safresh1For any type of reference, C<$Carp::RefArgFormatter> is checked (see below).
8956fb12b70Safresh1This variable is expected to be a code reference, and the current parameter
8966fb12b70Safresh1is passed in.  If this function doesn't exist (the variable is undef), or
8976fb12b70Safresh1it recurses into C<Carp>, or it otherwise throws an exception, this is
8986fb12b70Safresh1skipped, and Carp moves on to the next option, otherwise checking stops
8996fb12b70Safresh1and the string returned is used.
9006fb12b70Safresh1
9016fb12b70Safresh1=item 3.
9026fb12b70Safresh1
9036fb12b70Safresh1Otherwise, if neither C<CARP_TRACE> nor C<$Carp::RefArgFormatter> is
9046fb12b70Safresh1available, stringify the value ignoring any overloading.
9056fb12b70Safresh1
9066fb12b70Safresh1=back
9076fb12b70Safresh1
908898184e3Ssthen=head1 GLOBAL VARIABLES
909898184e3Ssthen
910898184e3Ssthen=head2 $Carp::MaxEvalLen
911898184e3Ssthen
912898184e3SsthenThis variable determines how many characters of a string-eval are to
913898184e3Ssthenbe shown in the output. Use a value of C<0> to show all text.
914898184e3Ssthen
915898184e3SsthenDefaults to C<0>.
916898184e3Ssthen
917898184e3Ssthen=head2 $Carp::MaxArgLen
918898184e3Ssthen
919898184e3SsthenThis variable determines how many characters of each argument to a
920898184e3Ssthenfunction to print. Use a value of C<0> to show the full length of the
921898184e3Ssthenargument.
922898184e3Ssthen
923898184e3SsthenDefaults to C<64>.
924898184e3Ssthen
925898184e3Ssthen=head2 $Carp::MaxArgNums
926898184e3Ssthen
927898184e3SsthenThis variable determines how many arguments to each function to show.
928b8851fccSafresh1Use a false value to show all arguments to a function call.  To suppress all
929b8851fccSafresh1arguments, use C<-1> or C<'0 but true'>.
930898184e3Ssthen
931898184e3SsthenDefaults to C<8>.
932898184e3Ssthen
933898184e3Ssthen=head2 $Carp::Verbose
934898184e3Ssthen
93591f110e0Safresh1This variable makes C<carp()> and C<croak()> generate stack backtraces
93691f110e0Safresh1just like C<cluck()> and C<confess()>.  This is how C<use Carp 'verbose'>
937898184e3Ssthenis implemented internally.
938898184e3Ssthen
939898184e3SsthenDefaults to C<0>.
940898184e3Ssthen
9416fb12b70Safresh1=head2 $Carp::RefArgFormatter
9426fb12b70Safresh1
9436fb12b70Safresh1This variable sets a general argument formatter to display references.
9446fb12b70Safresh1Plain scalars and objects that implement C<CARP_TRACE> will not go through
9456fb12b70Safresh1this formatter.  Calling C<Carp> from within this function is not supported.
9466fb12b70Safresh1
9476fb12b70Safresh1    local $Carp::RefArgFormatter = sub {
9486fb12b70Safresh1        require Data::Dumper;
949eac174f2Safresh1        Data::Dumper->Dump($_[0]); # not necessarily safe
9506fb12b70Safresh1    };
9516fb12b70Safresh1
952898184e3Ssthen=head2 @CARP_NOT
953898184e3Ssthen
954898184e3SsthenThis variable, I<in your package>, says which packages are I<not> to be
955898184e3Ssthenconsidered as the location of an error. The C<carp()> and C<cluck()>
956898184e3Ssthenfunctions will skip over callers when reporting where an error occurred.
957898184e3Ssthen
958898184e3SsthenNB: This variable must be in the package's symbol table, thus:
959898184e3Ssthen
960898184e3Ssthen    # These work
961898184e3Ssthen    our @CARP_NOT; # file scope
962898184e3Ssthen    use vars qw(@CARP_NOT); # package scope
963898184e3Ssthen    @My::Package::CARP_NOT = ... ; # explicit package variable
964898184e3Ssthen
965898184e3Ssthen    # These don't work
966898184e3Ssthen    sub xyz { ... @CARP_NOT = ... } # w/o declarations above
967898184e3Ssthen    my @CARP_NOT; # even at top-level
968898184e3Ssthen
969898184e3SsthenExample of use:
970898184e3Ssthen
971898184e3Ssthen    package My::Carping::Package;
972898184e3Ssthen    use Carp;
973898184e3Ssthen    our @CARP_NOT;
974898184e3Ssthen    sub bar     { .... or _error('Wrong input') }
975898184e3Ssthen    sub _error  {
976898184e3Ssthen        # temporary control of where'ness, __PACKAGE__ is implicit
977898184e3Ssthen        local @CARP_NOT = qw(My::Friendly::Caller);
978898184e3Ssthen        carp(@_)
979898184e3Ssthen    }
980898184e3Ssthen
981898184e3SsthenThis would make C<Carp> report the error as coming from a caller not
982898184e3Ssthenin C<My::Carping::Package>, nor from C<My::Friendly::Caller>.
983898184e3Ssthen
984898184e3SsthenAlso read the L</DESCRIPTION> section above, about how C<Carp> decides
985898184e3Ssthenwhere the error is reported from.
986898184e3Ssthen
987898184e3SsthenUse C<@CARP_NOT>, instead of C<$Carp::CarpLevel>.
988898184e3Ssthen
989898184e3SsthenOverrides C<Carp>'s use of C<@ISA>.
990898184e3Ssthen
991898184e3Ssthen=head2 %Carp::Internal
992898184e3Ssthen
993898184e3SsthenThis says what packages are internal to Perl.  C<Carp> will never
994898184e3Ssthenreport an error as being from a line in a package that is internal to
995898184e3SsthenPerl.  For example:
996898184e3Ssthen
997898184e3Ssthen    $Carp::Internal{ (__PACKAGE__) }++;
998898184e3Ssthen    # time passes...
999898184e3Ssthen    sub foo { ... or confess("whatever") };
1000898184e3Ssthen
1001898184e3Ssthenwould give a full stack backtrace starting from the first caller
1002898184e3Ssthenoutside of __PACKAGE__.  (Unless that package was also internal to
1003898184e3SsthenPerl.)
1004898184e3Ssthen
1005898184e3Ssthen=head2 %Carp::CarpInternal
1006898184e3Ssthen
1007898184e3SsthenThis says which packages are internal to Perl's warning system.  For
1008898184e3Ssthengenerating a full stack backtrace this is the same as being internal
1009898184e3Ssthento Perl, the stack backtrace will not start inside packages that are
1010898184e3Ssthenlisted in C<%Carp::CarpInternal>.  But it is slightly different for
1011898184e3Ssthenthe summary message generated by C<carp> or C<croak>.  There errors
1012898184e3Ssthenwill not be reported on any lines that are calling packages in
1013898184e3SsthenC<%Carp::CarpInternal>.
1014898184e3Ssthen
1015898184e3SsthenFor example C<Carp> itself is listed in C<%Carp::CarpInternal>.
1016898184e3SsthenTherefore the full stack backtrace from C<confess> will not start
1017898184e3Sstheninside of C<Carp>, and the short message from calling C<croak> is
1018898184e3Ssthennot placed on the line where C<croak> was called.
1019898184e3Ssthen
1020898184e3Ssthen=head2 $Carp::CarpLevel
1021898184e3Ssthen
1022898184e3SsthenThis variable determines how many additional call frames are to be
1023898184e3Ssthenskipped that would not otherwise be when reporting where an error
1024898184e3Ssthenoccurred on a call to one of C<Carp>'s functions.  It is fairly easy
1025898184e3Ssthento count these call frames on calls that generate a full stack
1026898184e3Ssthenbacktrace.  However it is much harder to do this accounting for calls
1027898184e3Ssthenthat generate a short message.  Usually people skip too many call
1028898184e3Ssthenframes.  If they are lucky they skip enough that C<Carp> goes all of
1029898184e3Ssthenthe way through the call stack, realizes that something is wrong, and
1030898184e3Ssthenthen generates a full stack backtrace.  If they are unlucky then the
1031898184e3Ssthenerror is reported from somewhere misleading very high in the call
1032898184e3Ssthenstack.
1033898184e3Ssthen
1034898184e3SsthenTherefore it is best to avoid C<$Carp::CarpLevel>.  Instead use
1035898184e3SsthenC<@CARP_NOT>, C<%Carp::Internal> and C<%Carp::CarpInternal>.
1036898184e3Ssthen
1037898184e3SsthenDefaults to C<0>.
1038898184e3Ssthen
1039898184e3Ssthen=head1 BUGS
1040898184e3Ssthen
1041898184e3SsthenThe Carp routines don't handle exception objects currently.
1042898184e3SsthenIf called with a first argument that is a reference, they simply
1043898184e3Ssthencall die() or warn(), as appropriate.
1044898184e3Ssthen
1045898184e3Ssthen=head1 SEE ALSO
1046898184e3Ssthen
1047898184e3SsthenL<Carp::Always>,
1048898184e3SsthenL<Carp::Clan>
1049898184e3Ssthen
1050b8851fccSafresh1=head1 CONTRIBUTING
1051b8851fccSafresh1
1052b8851fccSafresh1L<Carp> is maintained by the perl 5 porters as part of the core perl 5
1053b8851fccSafresh1version control repository. Please see the L<perlhack> perldoc for how to
1054b8851fccSafresh1submit patches and contribute to it.
1055b8851fccSafresh1
1056898184e3Ssthen=head1 AUTHOR
1057898184e3Ssthen
1058898184e3SsthenThe Carp module first appeared in Larry Wall's perl 5.000 distribution.
1059898184e3SsthenSince then it has been modified by several of the perl 5 porters.
1060898184e3SsthenAndrew Main (Zefram) <zefram@fysh.org> divested Carp into an independent
1061898184e3Ssthendistribution.
1062898184e3Ssthen
1063898184e3Ssthen=head1 COPYRIGHT
1064898184e3Ssthen
10656fb12b70Safresh1Copyright (C) 1994-2013 Larry Wall
1066898184e3Ssthen
10676fb12b70Safresh1Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
1068898184e3Ssthen
1069898184e3Ssthen=head1 LICENSE
1070898184e3Ssthen
1071898184e3SsthenThis module is free software; you can redistribute it and/or modify it
1072898184e3Ssthenunder the same terms as Perl itself.
1073