I'd like to print some output to the terminal in color when the terminal supports colors, print it plain otherwise. Also, I'd like no color when the program is not run interactively, e.g. when piped into grep.
What's the best way to do this in Perl? I'm hoping for some API that's sort of like this:
printColorMaybe( RED, "Hi", PLAIN, " mom!\n" );
where the implementation will ignore the color codes when not appropriate.
Term::ANSIColor
to produced colored output.
-t STDOUT
to test whether standard output is opened to a terminal.
$ENV{ANSI_COLORS_DISABLED}
to dynamically disable Term::ANSIColor
.
use Term::ANSIColor;
$ENV{ANSI_COLORS_DISABLED}++ unless -t STDOUT;
print colored("Hi","red")," mom!\n";