Alex Rivera | Logout

Coloring a perl die message

Asked 2011-04-17T04:54:13.110
12

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?

Here is the code block in question;

#!/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';
}

Update

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.

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?

Update 2

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

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

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

Edit
Report

1 Answer

4

I’m sure an END{} block in which you reset the terminal back to its blackness is the cleanest solution. That’s what such things are for.

Do NOT screw around with $SIG{__DIE__}, or you will be unhappy. Nobody realizes it gets called even for trapped exceptions!!

answered 2011-04-17T05:32:44.050

Your Answer