perl - 为 perl die 消息着色

标签 perl

我想在我的 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';
}

更新

它有效,但现在我无法摆脱模具语句中说明它发生在哪一行的部分。
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::ANSIColor 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";

关于perl - 为 perl die 消息着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691570/

相关文章:

linux - perl 解压文件

perl - Scalar::Util Looks_like_number返回数字类型

string - 在 Perl 中将所有参数作为字符串传递给子例程

apache - 如何在mod_perl下启用perl调试器?

Perl Mojolicious : chaining Promises

perl - 如何从命令行使用 ActivePerl 的 PPM 4?

perl - Chop map 的所有键(使用更少的代码)

perl - 解密此语法错误

regex - 电影抓取器,正则表达式并没有抓取每部电影

perl - 在 perldoc 中使撇号正确呈现