tags:

views:

1266

answers:

4

People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?

+8  A: 

carp works better for debugging within modules. If you are only writing a simple script, there is no benefit. From the Carp documenation:

The Carp routines are useful in your own modules because they act like die() or warn(), but with a message which is more likely to be useful to a user of your module. In the case of cluck, confess, and longmess that context is a summary of every call in the call-stack. For a shorter message you can use carp or croak which report the error as being from where your module was called. There is no guarantee that that is where the error was, but it is a good educated guess.

jvasak
+18  A: 

carp gives you more info as to where the the message comes from (context)

#!/usr/bin/perl

use Carp;

foo();
bar();
baz();

sub foo {
  warn "foo";
}

sub bar {
  carp "bar";
}

sub baz {
  foo();
  baz();
}

produces

foo at ./foo.pl line 9.
bar at ./foo.pl line 13
        main::bar() called at ./foo.pl line 6
foo at ./foo.pl line 10.
bar at ./foo.pl line 14
        main::bar() called at ./foo.pl line 19
        main::baz() called at ./foo.pl line 7

kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.

derby
+10  A: 

I use warn for scripts and simple programs, and Carp inside any modules. The Carp subroutines use the filename and line number where your current subroutine was called so it's easier to find who's causing the problem (not just where the problem manifested itself).

Damian recommends Carp instead of warn in "Reporting Failure" in Perl Best Practices, but doesn't make the distinction between scripts as top-level code constructs and modules as components that programs use.

I've mostly not cared about that lately because I've been using Log::Log4perl to handle all of that.

brian d foy
+7  A: 

Carp reports errors from the caller's perspective. This is useful for modules where you typically want to warn about incorrect usage (e.g. a missing argument) and identify the place where the error occurred as opposed to where it was detected. This is especially important for utility functions that might be used in many places.

Most authors use warn in scripts and carp in modules. Occasionally I use warn inside a module when I want the error message to reflect a problem in the module's implementation (e.g. a case that it should support but doesn't.) It's arguable that cluck would be better in such situations as it provides a full stack backtrace.

Michael Carman