Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use Carp instead of warn in Perl?

Tags:

module

perl

carp

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

like image 526
Frew Schmidt Avatar asked Oct 09 '08 19:10

Frew Schmidt


People also ask

What is use carp in Perl?

For a shorter message you can use carp() or croak() which report the error as being from where your module was called. shortmess() returns the contents of this error message. There is no guarantee that that is where the error was, but it is a good educated guess.

What is croak in Perl?

You use croak when it's something your caller isn't doing right. die "error: $!" indicates the error is on the line where the error occured. croak "error: $!" indicates the error is on the line where the caller called your code.


2 Answers

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

#!/usr/bin/perl  use Carp;  foo(); bar(); baz();  sub foo {   warn "foo"; }  sub bar {   carp "bar"; }  sub baz {   foo();   bar();  } 

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.

like image 186
derby Avatar answered Sep 20 '22 08:09

derby


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.

like image 38
brian d foy Avatar answered Sep 22 '22 08:09

brian d foy