着色perl die消息

ian*_*215 11 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';
}
Run Code Online (Sandbox Code Playgroud)

更新

它工作但现在我无法摆脱模具陈述的部分,说明它发生了什么线.

Loading configuration file
/etc/solignis/config.xml not found!
 at discovery.pl line 50.
Run Code Online (Sandbox Code Playgroud)

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

更新2

根据你的所有建议,我把它拼凑在一起.

print STDERR RED, "$config_file_path not found!";
die RESET, "\n";
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常.使用Term :: ANSIColor 1的常量是我需要的完美的东西.

Bri*_*ach 16

dieprint正在进行STDOUT时正在打印到STDERR .

print STDERR color 'red';
die "$config_file_path not found!\n";
Run Code Online (Sandbox Code Playgroud)

请注意......你刚刚去世了.您的"重置"不会被打印出来

你想将它连接到你的die:

die color 'red' . "$config_file_path not found!" . color 'reset';
Run Code Online (Sandbox Code Playgroud)

您还可以使用常量:

use Term::ANSIColor qw(:constants);

die RED, "THis is death!", RESET, "\n";
Run Code Online (Sandbox Code Playgroud)

编辑:对不起 - 并摆脱"它发生的地方"部分,连接\n到最后:

die color 'red' . "$config_file_path not found!" . color 'reset' . "\n";
Run Code Online (Sandbox Code Playgroud)


Sda*_*ons 5

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

UseTerm::ANSIColorcolored函数,它似乎在末尾自动添加了 ANSI 重置序列:

die colored( "$config_file_path not found!\n", 'red' );
Run Code Online (Sandbox Code Playgroud)

使用常量接口Term::ANSIColor

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

或者

die RED, "$config_file_path not found!\n", RESET;
Run Code Online (Sandbox Code Playgroud)

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