Handling Warnings

Learn how to handle warnings in Perl.

While there’s more than one way to write a working Perl program, some of those ways can be confusing, unclear, and even incorrect. Perl’s warnings system can help us avoid these situations.

Producing warnings

Use the warn built-in to emit a warning:

Press + to interact
warn 'Something went wrong!';

warn prints a list of values to the STDERR filehandle. Perl will append the filename and line number of the warn call unless the last element of the list ends in a newline.

The carp() function

The core Carp module extends Perl’s warning mechanisms. Its carp() function reports a warning from the perspective of the calling code. Consider a function like:

Press + to interact
use Carp 'carp';
sub only_two_arguments {
my ($lop, $rop) = @_;
carp( 'Too many arguments provided' ) if @_ > 2;
return $lop * $rop;
}
say only_two_arguments(1, 2, 3);

The arity warning will include the filename and line number of the calling code, not only_two_arguments(). The cluck() of Carp is similar, but it produces a backtrace of all function calls that led to the current function.

The verbose mode of Carp adds backtraces to all warnings produced by carp() and croak() throughout the entire program:

perl -MCarp=verbose my_prog.pl

Use Carp when writing modules instead of warn or die.

Note: Sometimes, you’ll have to debug code written without the use of carp() or ...