Carp

use Carp;
croak "We're outta here!";

use Carp qw(:DEFAULT cluck);
cluck "This is how we got here!";

The Carp module lets you write modules whose functions report errors the way built-in operators report errors—from the perspective of the users of your module. The Carp module supplies routines that you use much like the standard built-in functions warn and die, but that change the filename and line number so it looks like the error originated from the user's code instead of your code. In short, Carp is great way to misdirect blame.

There are actually four functions. The carp function works like the warn operator, but with caller-relative filename and line number information. The croak function works like die does—raising an exception—but again gives caller-relative information. If you prefer a longer lament, use cluck and confess instead of carp and croak respectively, and you'll get a full stack backtrace reporting who called whom and with what arguments (in the library with a lead pipe, no doubt). You have to import cluck explicitly, because it's not normally exported. People don't often want full stack traces on mere warnings, for some reason.

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.