为 perl die 消息着色 [英] Coloring a perl die message

查看:38
本文介绍了为 perl die 消息着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change the color of a die message in my perl script. I am currently using Term::ANSIColor to do other color changing in my script. The problem I run into with die messages is once the script dies it cannot reset the color to the terminal default and the terminal prompt is whatever color was last used in my script. In this case it turns it red.

知道如何让脚本死掉但仍将颜色改回来吗?

Any idea how I can have the script die but still change the color back?

这是有问题的代码块;

#!/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 statment 中说明它发生在哪一行的部分.

It works but now I am not able to get rid of the part of the die statment that says what line it happened on.

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

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

Normally I just add a line break the die function and that eliminates any of the normal error output from die. Any idea why its doing that?

更新 2

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

Based on all of your recommendations, I cobbled this together.

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

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

It seems to work correctly. Using the constants for Term::ANSIColor1 was a perfect thing I needed to simply things.

推荐答案

die 正在打印到 STDERR 而 print 正在去 STDOUT.

die is printing to STDERR while print is going to STDOUT.

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

请注意……你刚刚死了.您的重置"不会被打印

Note that ... you just died. Your 'reset' isn't going to be printed

你想把它连接到你的 die 上:

You want to concatenate it onto your die:

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

你也可以使用常量:

use Term::ANSIColor qw(:constants);

die RED, "THis is death!", RESET, "\n";

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

Sorry - And to get rid of the "where it happened" part, concatenate a \n to the end:

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

这篇关于为 perl die 消息着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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