包裹Perl“die”和“警告”在一个实用程序子程序中 [英] Wrapping Perl "die" and "warn" in a utility subroutine

查看:193
本文介绍了包裹Perl“die”和“警告”在一个实用程序子程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个小型子程序,可以以一致的方式装饰所有错误消息,而不必将其全部复制到我的程序周围。

I want to write a small subroutine that can decorate all error messages in a consistent way instead of having to copy it all around my program.

然而,我想要行号来自于被调用的地方,而不是从死亡 / 警告发生的地方。

However I want the line numbers to be from where it was called, not from where the die/warn occurred.

在CI中只会使用预处理器宏,但是Perl没有。实现这一点的最好方法是什么?

In C I would just use a preprocessor macro, but Perl does not have those. What is the best way to implement this?

推荐答案

使用鲤鱼发出警告/错误。你可以使用 __ WARN __ __ DIE __ 钩子来影响什么 warn 打印到 STDERR 流,并抛出死亡。请注意,它们是完全不同的。

Use Carp for warnings/errors. You can use __WARN__ and __DIE__ hooks to affect what warn prints to the STDERR stream and how die is thrown. Note that they are quite different.

use warnings;
use strict;
use feature 'say';

use Carp;

$SIG{__WARN__} = \&wrap_warn;

sub wrap_warn {
    print "WARNING: @_";
} 

sub level_2 { 
    say "Print from level_2";
    carp "carp from level_2(@_)"; 
}

sub level_1 {
    level_2(@_);
}

level_1("from main");

打印到 STDOUT

Print from level_2
WARNING: carp from level_2(from main) at wrap_warn.pl line 19.
        main::level_2('from main') called at wrap_warn.pl line 15
        main::level_1('from main') called at wrap_warn.pl line 22

如果你想让它仍然去 STDERR 然后使用打印STDERR警告:@_;

If you want this to still go to STDERR then use print STDERR "WARNING: @_";

确保仔细阅读有关 %SIG warn ,至少。

Make sure to carefully read about %SIG in perlvar and warn, at least.

虽然您希望这是全球性的,但我想提一下本地化的变化是g如果可能的话,你们想要什么。以下是此帖子的示例a>,还有更多。

While it seems that you want this to be global, I'd like to mention that local-izing changes like this is generally what one wants, if possible. There's an example in this post, and more out there.

这篇关于包裹Perl“die”和“警告”在一个实用程序子程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆