15.5. Changing Text ColorProblemYou want text to appear in different colors on the screen. For instance, you want to emphasize a mode line or highlight an error message. SolutionUse the CPAN module Term::ANSIColor to send the ANSI color-change sequences to the user's terminal: use Term::ANSIColor; print color("red"), "Danger, Will Robinson!\n", color("reset"); print "This is just normal text.\n"; print colored("<BLINK>Do you hurt yet?</BLINK>", "blink"); Or, you can use convenience functions from Term::ANSIColor: use Term::ANSIColor qw(:constants); print RED, "Danger, Will Robinson!\n", RESET; DiscussionTerm::ANSIColor prepares escape sequences that some (but far from all) terminals will recognize. For example, if you normally launch a color-xterm , this recipe will work. If you normally use the normal xterm program, or have a vt100 in your kitchen, it won't.
There are two ways of using the module: either by calling the exported functions Attributes can be a combination of colors and controls. The colors are black, red, green, yellow, blue, magenta, on_block, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, and on_white. (Apparently orange and purple don't matter.) The controls are clear, reset, bold, underline, underscore, blink, reverse, and concealed. Clear and reset are synonyms, as are underline and underscore. Reset restores the colors to the way they were when the program started, and concealed makes foreground and background colors the same. You can combine attributes: # rhyme for the deadly coral snake print color("red on_black"), "venom lack\n"; print color("red on_yellow"), "kill that fellow\n"; print color("green on_cyan blink"), "garish!\n"; print color("reset"); We could have written this as: print colored("venom lack\n", "red", on_black"); print colored("kill that fellow\n", "red", "on_yellow"); print colored("garish!\n", "green", "on_cyan", "blink"); or as: use Term::ANSIColor qw(:constants); print BLACK, ON_WHITE, "black on white\n"; print WHITE, ON_BLACK, "white on black\n"; print GREEN, ON_CYAN, BLINK, "garish!\n"; print RESET;
Here,
It's important to END { print color("reset") } to ensure the colors will be reset when your program finishes.
Attributes that span lines of text can confuse some programs or devices. If this becomes a problem, either manually set the attributes at the start of each line, or use $Term::ANSIColor::EACHLINE = $/; print colored(<<EOF, RED, ON_WHITE, BOLD, BLINK); This way each line has its own attribute set. EOF See AlsoThe documentation for the Term::AnsiColor module from CPAN |
|