Why should I use Carp instead of warn in Perl?

大城市里の小女人 提交于 2019-12-03 10:45:33

问题


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


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/188738/why-should-i-use-carp-instead-of-warn-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!