O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reporting Errors and Warnings Like Built-Ins

Problem

You want to generate errors and warnings in your modules, but when you use warn or die, the user sees your own filename and line number. You’d like your functions to act like built-ins and report messages from the perspective of the user’s code not your own.

Solution

The standard Carp module provides functions to do this. Use carp instead of warn. Use croak (for a short message) and confess (for a long message) instead of die.

Discussion

Like built-ins, some of your module’s functions generate warnings or errors if all doesn’t go well. Think about sqrt: when you pass it a negative number (and you haven’t used the Math::Complex module), an exception is raised, producing a message such as "Can't take sqrt of -3 at /tmp/negroot line 17", where /tmp/negroot is the name of your own program. But if you write your own function that dies, perhaps like this:

sub even_only {
    my $n = shift;
    die "$n is not even" if $n & 1;  # one way to test
    #....
}

then the message will say it’s coming from the file your even_only function was itself compiled in, rather than from the file the user was in when they called your function. That’s where the Carp module comes in handy. Instead of using die, use croak instead:

use Carp;
sub even_only {
    my $n = shift;
    croak "$n is not even" if $n % 2;  # here's another
    #....
}

If you just want to complain about something, but have the message report where in the user’s code the problem occurred, call carp instead of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required