为什么我应该在 Perl 中使用 Carp 而不是 warn ?
人们总是给我举鲤鱼的例子,而不是警告我。 为什么? 是什么让鲤鱼比警告更好?
People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
carp 为您提供了有关消息来自何处(上下文)的更多信息,
对于这个小程序来说有点
愚蠢,但当您想知道谁调用了吹毛求疵的方法时,它会派上用场。
carp gives you more info as to where the message comes from (context)
produces
kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.
我对脚本和简单程序使用
warn
,并在任何模块中使用Carp
。 Carp 子例程使用当前子例程被调用的文件名和行号,因此可以更轻松地找到导致问题的人(而不仅仅是问题出现的位置)。Damian 在Perl 最佳实践中的“报告失败”中推荐使用
Carp
而不是warn
,但并未将脚本作为顶级进行区分代码结构和模块作为程序使用的组件。我最近基本上不关心这个,因为我一直在使用 Log::Log4perl来处理这一切。
I use
warn
for scripts and simple programs, andCarp
inside any modules. TheCarp
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 ofwarn
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.
carp 更适合在模块内进行调试。 如果您只是编写一个简单的脚本,那么没有任何好处。 来自 Carp 文档:
carp works better for debugging within modules. If you are only writing a simple script, there is no benefit. From the Carp documenation:
Carp
从调用者的角度报告错误。 这对于您通常想要警告错误使用(例如缺少参数)并识别错误发生的位置而不是检测到错误的位置的模块很有用。这对于可能在许多地方使用的实用函数尤其重要。大多数作者在脚本中使用
warn
,在模块中使用carp
。 有时,当我希望错误消息反映模块实现中的问题(例如,它应该支持但不支持的情况)时,我会在模块内使用warn
。 /code> 在这种情况下会更好,因为它提供了完整的堆栈回溯。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 andcarp
in modules. Occasionally I usewarn
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 thatcluck
would be better in such situations as it provides a full stack backtrace.