Carp :: carp在Perl中做了什么?

thi*_*van 0 perl carp

任何人都可以carp用Perl代码示例解释子程序吗?

mob*_*mob 14

perldoc鲤鱼.

carp是Perl warn函数的替代方法,它使用堆栈跟踪信息向您显示您调用发出警告的函数的位置.这比warn告诉你警告发生在哪里的行为更有帮助.

一个例子:

这个程序:

1: sub square_root {
2:  my $arg = shift;
3:  if ($arg < 0) {
4:    warn "Can't take square root of a negative number";
5:  } else {
6:    return sqrt($arg);
7:  }
8: }
9: print square_root(-4);
Run Code Online (Sandbox Code Playgroud)

告诉你:

Can't take square root of a negative number at carpdemo.pl line 4.
Run Code Online (Sandbox Code Playgroud)

但如果我们warn改为carp:

1: use Carp;
2: sub square_root {
3:  my $arg = shift;
4:  if ($arg < 0) {
5:    carp "Can't take square root of a negative number";
6:  } else {
7:    return sqrt($arg);
8:  }
9: }
10: print square_root(-4);
Run Code Online (Sandbox Code Playgroud)

它告诉你:

Can't take square root of a negative number at carpdemo.pl line 4
        main::square_root(-4) called at carpdemo.pl line 10
Run Code Online (Sandbox Code Playgroud)

额外的信息行有助于跟踪您可能错误地使用函数或模块的位置.

  • 堆栈跟踪:http://en.wikipedia.org/wiki/Stack_trace - 您当前所处的功能列表 (2认同)