【问题标题】:Coloring a perl die message为 perl die 消息着色
【发布时间】:2011-08-07 04:30:15
【问题描述】:

我想在我的 perl 脚本中更改 die 消息的颜色。我目前正在使用Term::ANSIColor 在我的脚本中进行其他颜色更改。我遇到的死亡消息问题是,一旦脚本终止,它就无法将颜色重置为终端默认值,并且终端提示符是我的脚本中最后使用的任何颜色。在这种情况下,它会变成红色。

知道我怎样才能让脚本死掉但仍然改变颜色吗?

这里是有问题的代码块;

#!/usr/bin/perl
use strict;
use warnings;
require Term::ANSIColor;
use Term::ANSIColor;

print "Loading configuration file\n";

# Check if the specified configuration file exists, if not die
if (! -e $config_file_path) {
    print color 'red';
    die "$config_file_path not found!\n";
    print color 'reset';
} else {
    print color 'green';
    print "$config_file_path loaded\n";
    print color 'reset';
}

更新

它有效,但现在我无法摆脱 die 语句中说明它发生在哪一行的部分。

Loading configuration file
/etc/solignis/config.xml not found!
 at discovery.pl line 50.

通常我只是添加一个换行的 die 函数,它消除了 die 的任何正常错误输出。知道为什么要这样做吗?

更新 2

根据您的所有建议,我拼凑起来。

print STDERR RED, "$config_file_path not found!";
die RESET, "\n";

它似乎工作正常。使用 Term::ANSIColor1 的常量是一件完美的事情,我需要简单的事情。

【问题讨论】:

    标签: perl


    【解决方案1】:

    die 正在打印到 STDERR,而print 正在打印到 STDOUT。

    print STDERR color 'red';
    die "$config_file_path not found!\n";
    

    请注意……你刚刚死了。您的“重置”不会被打印出来

    你想把它连接到你的die

    die color 'red' . "$config_file_path not found!" . color 'reset';
    

    你也可以使用常量:

    use Term::ANSIColor qw(:constants);
    
    die RED, "THis is death!", RESET, "\n";
    

    编辑:抱歉 - 为了摆脱“发生的地方”部分,将 \n 连接到末尾:

    die color 'red' . "$config_file_path not found!" . color 'reset' . "\n";
    

    【讨论】:

    • 知道了 - 抱歉,我忘记了 \n 是这样做的。 color 函数所做的只是返回一个控制字符,终端将其解释为颜色变化,因此您将该字符与连接一起包含在字符串中。
    • +1 为您服务,使用 Term::ANSIColor qw(:constants); 的想法是一个很棒的想法。谢谢
    • 更正,您的更新解决方案是完美的。我喜欢它放在一条线上的方式。
    • 请注意,您可以对常量执行相同操作 - 只需将 \n 粘贴在末尾(我刚刚也更新了)
    • 是的,我想通了,我从不费心使用 concats。所以我真的可以大大减少我的代码。
    【解决方案2】:

    有几种方法可以做到这一点。

    使用Term::ANSIColorcolored函数,貌似会在末尾自动添加ANSI复位序列:

    die colored( "$config_file_path not found!\n", 'red' );
    

    使用来自Term::ANSIColor的常量接口:

    use Term::ANSIColor qw( :constants );
    $Term::ANSIColor::AUTORESET = 1;
    die RED "$config_file_path not found!\n";
    

    die RED, "$config_file_path not found!\n", RESET;
    

    您也可以捕获$SIG{__DIE__},或使用带有coderef 的END 块,并在打印其参数后重置它。 (这些可能不是最好的想法,但它们可以让您在几乎任何退出情况下重置颜色。)

    【讨论】:

    • END{ } 块是最好的方法。 ++
    【解决方案3】:

    您可以使用__DIE__ 处理程序:

    $SIG{'__DIE__'} = sub {
        print color 'reset';
    };
    

    来自perldoc perlvar

    由于实施故障, $SIG{__DIE__} 钩子被称为偶数 在eval() 内。

    因此,您可能不应该使用这种技术。

    【讨论】:

    • 为什么每个被捕获的异常都应该打印那个杂物?糟糕!
    • tchrist:添加了关于它的引用。谢谢。
    【解决方案4】:

    我确信将终端重置为黑色的END{} 块是最干净的解决方案。这就是这些东西的用途。

    不要不要$SIG{__DIE__}搞混,否则你会不高兴的。没有人意识到即使是 trapped 异常也会调用它!

    【讨论】:

    • 是的,我尝试了$SIG{__DIE__},尽管我不知道它的作用。无论如何,它对我不起作用。
    • END{ } 块是最好的方法。 ++
    猜你喜欢
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多