home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / lib / Carp.pm < prev    next >
Text File  |  1995-07-03  |  2KB  |  73 lines

  1. package Carp;
  2.  
  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.  
  27. # This package implements handy routines for modules that wish to throw
  28. # exceptions outside of the current package.
  29.  
  30. $CarpLevel = 0;        # How many extra package levels to skip on carp.
  31.  
  32. require Exporter;
  33. @ISA = Exporter;
  34. @EXPORT = qw(confess croak carp);
  35.  
  36. sub longmess {
  37.     my $error = shift;
  38.     my $mess = "";
  39.     my $i = 1 + $CarpLevel;
  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.  
  49. sub shortmess {    # Short-circuit &longmess if called via multiple packages
  50.     my $error = $_[0];    # Instead of "shift"
  51.     my ($curpack) = caller(1);
  52.     my $extra = $CarpLevel;
  53.     my $i = 2;
  54.     my ($pack,$file,$line,$sub);
  55.     while (($pack,$file,$line,$sub) = caller($i++)) {
  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.     }
  64.     }
  65.     goto &longmess;
  66. }
  67.  
  68. sub confess { die longmess @_; }
  69. sub croak { die shortmess @_; }
  70. sub carp { warn shortmess @_; }
  71.  
  72. 1;
  73.