简体   繁体   中英

Color terminal output in Perl

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, eg 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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM