Term::ANSIColor(3perl)

✨ NAME ✨

hiii bestie πŸ’– welcome to Term::ANSIColor, live from the Perl Programmers Reference Guide.

Term::ANSIColor β€” Color screen output using ANSI escape sequences πŸŒˆπŸ’…


πŸ¦‹ SYNOPSIS πŸ¦‹

okay so here's the whole vibe, no cap:

use Term::ANSIColor;
print color('bold blue');
print "This text is bold blue.\n";
print color('reset');
print "This text is normal.\n";
print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
print "This text is normal.\n";
print colored(['yellow on_magenta'], 'Yellow on magenta.', "\n");
print colored(['red on_bright_yellow'], 'Red on bright yellow.', "\n");
print colored(['bright_red on_black'], 'Bright red on black.', "\n");
print "\n";

# Map escape sequences back to color names.
use Term::ANSIColor 1.04 qw(uncolor);
my @names = uncolor('01;31');
print join(q{ }, @names), "\n";

# Strip all color escape sequences.
use Term::ANSIColor 2.01 qw(colorstrip);
print colorstrip("\e[1mThis is bold\e[0m"), "\n";

# Determine whether a color is valid.
use Term::ANSIColor 2.02 qw(colorvalid);
my $valid = colorvalid('blue bold', 'on_magenta');
print "Color string is ", $valid ? "valid\n" : "invalid\n";

# Create new aliases for colors.
use Term::ANSIColor 4.00 qw(coloralias);
coloralias('alert', 'red');
print "Alert is ", coloralias('alert'), "\n";
print colored("This is in red.", 'alert'), "\n";

use Term::ANSIColor qw(:constants);
print BOLD, BLUE, "This text is in bold blue.\n", RESET;

use Term::ANSIColor qw(:constants);
{
    local $Term::ANSIColor::AUTORESET = 1;
    print BOLD BLUE "This text is in bold blue.\n";
    print "This text is normal.\n";
}

use Term::ANSIColor 2.00 qw(:pushpop);
print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
print RESET BRIGHT_BLUE "This text is just bright blue.\n";
print POPCOLOR "Back to red on green.\n";
print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
print "This text is red on green.\n";
{
    local $Term::ANSIColor::AUTOLOCAL = 1;
    print ON_BLUE "This text is red on blue.\n";
    print "This text is red on green.\n";
}
print POPCOLOR "Back to whatever we started as.\n";

like, iconic honestly 🫢


🌸 DESCRIPTION 🌸

okay so this module has two whole interfaces β€” one through color() and colored(), and the other through constants. it also serves up the utility functions uncolor(), colorstrip(), colorvalid(), and coloralias(), which you have to explicitly import to use them (peep the "SYNOPSIS" for the receipts).

if you're using Term::ANSIColor in a console command, bestie, consider supporting the CLICOLOR standard β€” see "Supporting CLICOLOR" for more on that πŸ’…

and see "COMPATIBILITY" for the versions of Term::ANSIColor that introduced particular features, plus the versions of Perl that included them.

🎨 Supported Colors 🎨

so terminal emulators that support color split into four types: ones that only do eight colors, ones that do sixteen, ones that do 256, and ones that do 24-bit color. this module hands you the ANSI escape codes for all of them. these colors are called ANSI colors 0 through 7 (normal), 8 through 15 (16-color), 16 through 255 (256-color), and true color (which xterm calls direct-color).

now here's the messy part πŸ™ˆ β€” how colors 0 through 7 get interpreted often depends on whether the emulator does eight colors or sixteen. emulators that only do eight colors (like the Linux console) show colors 0 through 7 at normal brightness and just ignore colors 8 through 15, treating them the same as white. emulators that do sixteen colors, like gnome-terminal, normally show colors 0 through 7 as dim or darker versions, and colors 8 through 15 at normal brightness. on those, the "normal" white (color 7) usually shows up as pale grey, so you need bright white (15) if you actually want a real white. bright black is usually a dark grey, though some terminals show it as pure black. some sixteen-color terminal emulators also treat normal yellow (color 3) as orange or brown, and bright yellow (color 11) as yellow. the drama 😭

following the normal convention of sixteen-color emulators, this module gives you a pair of attributes for each color. for every normal color (0 through 7), the matching bright color (8 through 15) is just the normal color name with the string "bright_" stuck on the front. for example, "red" is color 1 and "bright_red" is color 9. same deal for background colors: "on_red" is the normal one and "on_bright_red" is the bright one. capitalize these strings for the constant interface ✨

unfortunately there is no way to know whether the current emulator supports more than eight colors, which makes picking colors genuinely hard. the most conservative choice is to use only the regular colors, since those at least display on all emulators. but ngl, they'll look dark on sixteen-color terminal emulators, including most common emulators in UNIX X environments. if you know the display is one of those emulators, you may want to use the bright variants instead. even better: give the user a way to configure the colors for a given application to fit their terminal emulator πŸ’–

for 256-color emulators, this module additionally provides "ansi0" through "ansi15", which are the same as colors 0 through 15 in sixteen-color emulators but use the 256-color escape syntax, plus "grey0" through "grey23" ranging from nearly black to nearly white, and a set of RGB colors. the RGB colors are of the form "rgbRGB" where R, G, and B are numbers from 0 to 5 giving the intensity of red, green, and blue. the grey and RGB colors are also available as "ansi16" through "ansi255" if you want simple names for all 256 colors. "on_" variants of all of these are provided too. on non-256-color terminals these colors may be ignored completely, or they may be misinterpreted and produce random behavior πŸ’€ and heads up: additional attributes such as blink, italic, or bold may not work with the 256-color palette.

for true color emulators, this module supports attributes of the form "rNNNgNNNbNNN" and "on_rNNNgNNNbNNN" for all values of NNN between 0 and 255. those are foreground and background colors respectively, with the RGB values given by the NNN numbers. on non-true-color terminals these may be ignored completely, or they may be misinterpreted and produce random behavior 😭

🧸 Function Interface 🧸

the function interface uses attribute strings to describe the colors and text attributes you wanna assign to text. the recognized non-color attributes are clear, reset, bold, dark, faint, italic, underline, underscore, blink, reverse, and concealed. quick note: clear and reset (reset to default attributes) are equivalent, dark and faint (dim and saturated) are equivalent, and underline and underscore are equivalent β€” so just use whichever feels most intuitive to you, bestie 🫢

fr fr: not all attributes are supported by all terminal types, and some terminals may not support any of these sequences. dark and faint, italic, blink, and concealed in particular are frequently just not implemented. it's giving "we tried" πŸ’€

the recognized normal foreground color attributes (colors 0 to 7) are:

black  red  green  yellow  blue  magenta  cyan  white

the corresponding bright foreground color attributes (colors 8 to 15) are:

bright_black  bright_red      bright_green  bright_yellow
bright_blue   bright_magenta  bright_cyan   bright_white

the recognized normal background color attributes (colors 0 to 7) are:

on_black  on_red      on_green  on yellow
on_blue   on_magenta  on_cyan   on_white

the recognized bright background color attributes (colors 8 to 15) are:

on_bright_black  on_bright_red      on_bright_green  on_bright_yellow
on_bright_blue   on_bright_magenta  on_bright_cyan   on_bright_white

for 256-color terminals, the recognized foreground colors are:

ansi0 .. ansi255
grey0 .. grey23

plus "rgbRGB" for R, G, and B values from 0 to 5, such as "rgb000" or "rgb515". similarly, the recognized background colors are:

on_ansi0 .. on_ansi255
on_grey0 .. on_grey23

plus "on_rgbRGB" for R, G, and B values from 0 to 5.

for true color terminals, the recognized foreground colors are "rRRRgGGGbBBB" for RRR, GGG, and BBB values between 0 and 255. similarly, the recognized background colors are "on_rRRRgGGGbBBB" for RRR, GGG, and BBB values between 0 and 255.

for any of the above listed attributes, case is not significant ✨

attributes, once set, last until they are unset (by printing the attribute "clear" or "reset"). please be careful to actually do this, or your attribute will outlive your script, and people get very annoyed at having their prompt and typing changed to weird colors 😭

color(ATTR[, ATTR ...])

color() takes any number of strings as arguments and considers them to be space-separated lists of attributes. it then forms and returns the escape sequence that sets those attributes. it does not print it out β€” it just returns it, so you'll have to print it yourself if you want it printed. that's on purpose, so you can save it as a string, pass it to something else, send it to a file handle, or do literally anything else you might care to do with it. color() throws an exception if you give it an invalid attribute 🚨

colored(STRING, ATTR[, ATTR ...]) colored(ATTR-REF, STRING[, STRING...])

as an aid in resetting colors, colored() takes a scalar as the first argument and any number of attribute strings as the second argument, and returns the scalar wrapped in escape codes so that the attributes will be set as requested before the string and reset to normal after the string. alternately, you can pass a reference to an array as the first argument, and then the contents of that array will be taken as attributes and color codes, and the remainder of the arguments as text to colorize πŸ’…

normally, colored() just puts attribute codes at the beginning and end of the string, but if you set $Term::ANSIColor::EACHLINE to some string, that string will be considered the line delimiter, and the attribute will be set at the beginning of each line of the passed string and reset at the end of each line. this is often desirable if the output contains newlines and you're using background colors, since a background color that persists across a newline is often interpreted by the terminal as providing the default background color for the next line. programs like pagers can also be confused by attributes that span lines. normally you'll want to set $Term::ANSIColor::EACHLINE to "\n" to use this feature.

Particularly consider setting $Term::ANSIColor::EACHLINE if you are interleaving output to standard output and standard error and you aren't flushing standard output (via autoflush() or setting $|). If you don't, the code to reset the color may unexpectedly sit in the standard output buffer rather than going to the display, causing standard error output to appear in the wrong color. like bestie pls flush your buffers, this is not the chaos we're aiming for 😭

  • uncolor(ESCAPE) β€” uncolor() does the opposite translation of color(), turning escape sequences into a list of strings matching the attributes those sequences set. And heads up: uncolor() will never return "ansi16" through "ansi255" β€” it prefers the "grey" and "rgb" names instead (same energy for "on_ansi16" through "on_ansi255"). it's giving reverse-engineering, and it ate πŸ’…
  • colorstrip(STRING[, STRING ...]) β€” colorstrip() removes all color escape sequences from the strings you hand it, returning the cleaned strings separately in array context or joined together in scalar context. Your arguments? Not modified. untouched, unbothered, exactly as they were ✨
  • colorvalid(ATTR[, ATTR ...]) β€” colorvalid() takes attribute strings just like color() does, and returns true if all the attributes are known and false otherwise. a lil vibe check for your attribute strings 🫢
  • coloralias(ALIAS[, ATTR ...]) β€” okay so if ATTR is specified, it gets interpreted as a list of space-separated strings naming attributes or existing aliases. When that happens, coloralias() sets up an alias called ALIAS for the set of attributes given by ATTR. From that moment forward, ALIAS can be passed into color(), colored(), and colorvalid() and it will mean exactly the same thing as that sequence of attributes in ATTR. One possible use? Giving more meaningful names to the 256-color RGB colors. naming things is a love language fr fr Only ASCII alphanumerics, ".", "_", and "-" are allowed in alias names.

If ATTR includes aliases, those aliases get expanded at definition time and their values get used to define the new alias. Which means: if you define an alias A in terms of another alias B, and then later redefine alias B, the value of alias A will not change. snapshot behavior, not live-updating. periodt πŸ’…

If ATTR is not specified, coloralias() returns the standard attribute or attributes that ALIAS is aliased to, if any, or undef if ALIAS doesn't exist. If it's aliased to multiple attributes, the return value will be a single string with the attributes separated by spaces.

This is the same facility used by the ANSI_COLORS_ALIASES environment variable (peep "ENVIRONMENT" below) β€” but you can use it at runtime, not just when the module loads. glow up ✨

Later invocations of coloralias() with the same ALIAS will override earlier aliases. There is no way to remove an alias. once it's in, it's in, bestie πŸ’€

Aliases have no effect on the return value of uncolor().

WARNING: Aliases are global and affect all callers in the same process. There is no way to set an alias limited to a particular block of code or a particular object. it's giving main character energy whether you want it or not 😭

✨ Constant Interface ✨

Alternately, if you import ":constants", you can use the following constants directly:

  CLEAR           RESET             BOLD            DARK
  FAINT           ITALIC            UNDERLINE       UNDERSCORE
  BLINK           REVERSE           CONCEALED

  BLACK           RED               GREEN           YELLOW
  BLUE            MAGENTA           CYAN            WHITE
  BRIGHT_BLACK    BRIGHT_RED        BRIGHT_GREEN    BRIGHT_YELLOW
  BRIGHT_BLUE     BRIGHT_MAGENTA    BRIGHT_CYAN     BRIGHT_WHITE

  ON_BLACK        ON_RED            ON_GREEN        ON_YELLOW
  ON_BLUE         ON_MAGENTA        ON_CYAN         ON_WHITE
  ON_BRIGHT_BLACK ON_BRIGHT_RED     ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
  ON_BRIGHT_BLUE  ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN  ON_BRIGHT_WHITE

These are the same as color('attribute'), and you can use them if you'd rather type:

print BOLD BLUE ON_WHITE "Text", RESET, "\n";

instead of:

print colored ("Text", 'bold blue on_white'), "\n";

(Note that the newline is kept separate to avoid confusing the terminal as described above, since a background color is being used. terminals are sensitive ok, be gentle πŸ₯Ί)

If you import ":constants256", you can use the following constants directly:

ANSI0 .. ANSI255
GREY0 .. GREY23

RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)

ON_ANSI0 .. ON_ANSI255
ON_GREY0 .. ON_GREY23

ON_RGBXYZ (for X, Y, and Z values from 0 to 5)

Note that ":constants256" does not include the other constants, so if you want to mix both, you need to include ":constants" as well. You may want to explicitly import at least "RESET", like:

use Term::ANSIColor 4.00 qw(RESET :constants256);

True color and aliases are not supported by the constant interface. sorry babe, that feature doesn't come in this flavor πŸ™ˆ

When using the constants, if you don't want to have to remember to add the ", RESET" at the end of each print line, you can set $Term::ANSIColor::AUTORESET to a true value. Then the display mode will automatically be reset if there's no comma after the constant. In other words, with that variable set:

print BOLD BLUE "Text\n";

will reset the display mode afterward, whereas:

print BOLD, BLUE, "Text\n";

will not. If you're using background colors, you will probably want to either use say() (in newer versions of Perl) or print the newline with a separate print statement, to avoid confusing the terminal. protect the terminal's peace 🫢

If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence over $Term::ANSIColor::AUTORESET, and the latter is ignored. only one of them gets the aux, sorry πŸ’…

The subroutine interface has an advantage over the constants interface: only two subroutines get exported into your namespace, versus thirty-eight in the constants interface, and aliases and true color attributes are supported. On the flip side, the constants interface has the advantage of better compile-time error checking β€” since misspelled names of colors or attributes in calls to color() and colored() won't be caught until runtime, whereas misspelled names of constants will be caught at compile time. So: pollute your namespace with almost two dozen subroutines you may not even use that often, or risk a silly bug by mistyping an attribute. Your choice, TMTOWTDI after all. πŸ‘‘

πŸŽ€ The Color Stack πŸŽ€

You can import ":pushpop" and maintain a stack of colors using PUSHCOLOR, POPCOLOR, and LOCALCOLOR. PUSHCOLOR takes the attribute string that starts its argument and pushes it onto a stack of attributes. POPCOLOR removes the top of the stack and restores the previous attributes set by the argument of a prior PUSHCOLOR. LOCALCOLOR surrounds its argument in a PUSHCOLOR and a POPCOLOR so that the color resets afterward. it's a stack bestie, last in first out, we love to see it πŸ¦‹

If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants will be implicitly preceded by LOCALCOLOR. In other words, the following:

{
    local $Term::ANSIColor::AUTOLOCAL = 1;
    print BLUE "Text\n";
}

is equivalent to:

print LOCALCOLOR BLUE "Text\n";

If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over $Term::ANSIColor::AUTORESET, and the latter is ignored. again: local ate, reset is on read πŸ’…

When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly important to not put commas between the constants. NO COMMAS, I'm so serious 😀

print PUSHCOLOR BLUE "Text\n";

will correctly push BLUE onto the top of the stack.

print PUSHCOLOR, BLUE, "Text\n";    # wrong!

will not, and a subsequent pop won't restore the correct attributes. PUSHCOLOR pushes the attributes set by its argument, which is normally a string of color constants. It can't ask the terminal what the current attributes are. it's not psychic, it just reads the string you gave it πŸ™ˆ

🌈 Supporting CLICOLOR 🌈

<https://bixense.com/clicolors/> proposes a standard for enabling and disabling color output from console commands using two environment variables, CLICOLOR and CLICOLOR_FORCE. Term::ANSIColor cannot automatically support this standard, since the correct action depends on where the output is going and Term::ANSIColor may be used in a context where colors should always be generated even if CLICOLOR is set in the environment. But you can use the supported environment variable ANSI_COLORS_DISABLED to implement CLICOLOR in your own programs with code like this:

if (exists($ENV{CLICOLOR}) && $ENV{CLICOLOR} == 0) {
    if (!$ENV{CLICOLOR_FORCE}) {
        $ENV{ANSI_COLORS_DISABLED} = 1;
    }
}

If you're using the constant interface, be sure to include this code before you use any color constants (like at the very top of your script), since this environment variable is only honored the first time a color constant is seen. timing is everything, bestie ⏰

Be aware that this will export ANSI_COLORS_DISABLED to any child processes of your program as well. it spreads, and that's on purpose (mostly) πŸ“

πŸ’– DIAGNOSTICS πŸ’–

okay bestie, this is the part where Perl yells at you (lovingly). each one has a letter code: (W) = warning, she's just side-eyeing you. (F) = fatal, dead, gone, we are NOT recovering. πŸ’€

  • Bad color mapping %s

(W) so the color mapping you put in ANSI_COLORS_ALIASES? not valid, couldn't be parsed, it's giving nothing. she ignored it. moving on.

  • Bad escape sequence %s

(F) you handed uncolor() an invalid ANSI escape sequence. that's not a vibe. that's a fatal error.

  • Bareword "%s" not allowed while "strict subs" in use

(F) you probably typo'd a constant color name, like here:

    $Foobar = FOOBAR . "This line should be blue\n";

or like:

    @Foobar = FOOBAR, "This line should be blue\n";

this only shows up under use strict β€” which, bestie, is another very good reason to run under use strict. ✨

  • Cannot alias standard color %s

(F) the alias name you passed to coloralias() matches a standard color name. standard color names are booked and busy, they cannot be aliased. periodt.

  • Cannot alias standard color %s in %s

(W) same thing, but in ANSI_COLORS_ALIASES. the color mapping was ignored.

  • Invalid alias name %s

(F) you passed an invalid alias name to coloralias(). alias names must consist only of alphanumerics, ".", "-", and "_". that's the whole guest list.

  • Invalid alias name %s in %s

(W) you specified an invalid alias name on the left hand of the equal sign in a color mapping in ANSI_COLORS_ALIASES. the color mapping was ignored.

  • Invalid attribute name %s

(F) you passed an invalid attribute name to color(), colored(), or coloralias(). nope.

  • Invalid attribute name %s in %s

(W) you specified an invalid attribute name on the right hand of the equal sign in a color mapping in ANSI_COLORS_ALIASES. the color mapping was ignored.

  • Name "%s" used only once: possible typo

(W) you probably typo'd a constant color name, like:

    print FOOBAR "This text is color FOOBAR\n";

honestly it's probably better to always use commas after constant names in order to force the next error. catch it early, bestie. πŸ¦‹

  • No comma allowed after filehandle

(F) you probably typo'd a constant color name, like:

    print FOOBAR, "This text is color FOOBAR\n";

and this is genuinely one of the main advantages of using the constants interface β€” you'll immediately know if you mistype a color name. iconic behavior, honestly.

  • No name for escape sequence %s

(F) the ANSI escape sequence passed to uncolor() contains escapes which aren't recognized and can't be translated to names. she doesn't know her, she can't name her.


🌈 ENVIRONMENT 🌈

  • ANSI_COLORS_ALIASES

this environment variable lets the user specify custom color aliases that will be understood by color(), colored(), and colorvalid(). none of the other functions will be affected, and no new color constants will be created. the custom colors are aliases for existing color names; no new escape sequences can be introduced. only alphanumerics, ".", "_", and "-" are allowed in alias names.

the format is:

    ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'

whitespace is ignored. the alias value can be a single attribute or a space-separated list of attributes.

for example the Solarized <https://ethanschoonover.com/solarized> colors can be mapped with:

    ANSI_COLORS_ALIASES='\
        base00=bright_yellow, on_base00=on_bright_yellow,\
        base01=bright_green,  on_base01=on_bright_green, \
        base02=black,         on_base02=on_black,        \
        base03=bright_black,  on_base03=on_bright_black, \
        base0=bright_blue,    on_base0=on_bright_blue,   \
        base1=bright_cyan,    on_base1=on_bright_cyan,   \
        base2=white,          on_base2=on_white,         \
        base3=bright_white,   on_base3=on_bright_white,  \
        orange=bright_red,    on_orange=on_bright_red,   \
        violet=bright_magenta,on_violet=on_bright_magenta'
heads up bestie: this environment variable is read and applied when the Term::ANSIColor module is loaded and is then subsequently ignored. changes to ANSI_COLORS_ALIASES after the module is loaded will have no effect. see coloralias() for an equivalent facility that can be used at runtime. πŸ’…
  • ANSI_COLORS_DISABLED

if this environment variable is set to a true value, all of the functions defined by this module (color(), colored(), and all of the constants) will not output any escape sequences and instead will just return the empty string or pass through the original text as appropriate. this is intended to support easy use of scripts using this module on platforms that don't support ANSI escape sequences. very "we're at a sleepover and the wifi is down" of her, honestly.

  • NO_COLOR

if this environment variable is set to any value, it suppresses generation of escape sequences the same as if ANSI_COLORS_DISABLED is set to a true value. this implements the <https://no-color.org/> informal standard. programs that want to enable color despite NO_COLOR being set will need to unset that environment variable before any constant or function provided by this module is used.


πŸŽ€ COMPATIBILITY πŸŽ€

the whole lore, in order, so you know exactly when every feature entered the chat:

  • Term::ANSIColor was first included with Perl in Perl 5.6.0.
  • The uncolor() function and support for ANSI_COLORS_DISABLED were added in Term::ANSIColor 1.04, included in Perl 5.8.0.
  • Support for dark was added in Term::ANSIColor 1.08, included in Perl 5.8.4.
  • The color stack, including the ":pushpop" import tag, PUSHCOLOR, POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was added in Term::ANSIColor 2.00, included in Perl 5.10.1.
  • colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added in Term::ANSIColor 2.02, both included in Perl 5.11.0.
  • Support for colors 8 through 15 (the "bright_" variants) was added in Term::ANSIColor 3.00, included in Perl 5.13.3.
  • Support for italic was added in Term::ANSIColor 3.02, included in Perl 5.17.1.
  • Support for colors 16 through 256 (the "ansi", "rgb", and "grey" colors), the ":constants256" import tag, the coloralias() function, and support for the ANSI_COLORS_ALIASES environment variable were added in Term::ANSIColor 4.00, included in Perl 5.17.8.
  • $Term::ANSIColor::AUTOLOCAL was changed to take precedence over $Term::ANSIColor::AUTORESET, rather than the other way around, in Term::ANSIColor 4.00, included in Perl 5.17.8.
  • "ansi16" through "ansi255", as aliases for the "rgb" and "grey" colors, and the corresponding "on_ansi" names and "ANSI" and "ON_ANSI" constants were added in Term::ANSIColor 4.06, included in Perl 5.25.7.
  • Support for true color (the "rNNNgNNNbNNN" and "on_rNNNgNNNbNNN" attributes), defining aliases in terms of other aliases, and aliases mapping to multiple attributes instead of only a single attribute was added in Term::ANSIColor 5.00.
  • Support for NO_COLOR was added in Term::ANSIColor 5.01.

⚠️ RESTRICTIONS ⚠️

okay so this is the part where we talk about the things she simply cannot do, and how to work around them. listen up.

both colored() and many uses of the color constants will add the reset escape sequence after a newline. if a program mixes colored output to standard output with output to standard error, this can result in the standard error text having the wrong color because the reset escape sequence hasn't yet been flushed to the display (since standard output to a terminal is line-buffered by default). 😭 to avoid this, either set autoflush() on STDOUT or set $Term::ANSIColor::EACHLINE to "\n".

it would be nice if one could leave off the commas around the constants entirely and just say:

    print BOLD BLUE ON_WHITE "Text\n" RESET;

but the syntax of Perl doesn't allow this. you need a comma after the string. (of course, you may consider it a bug that commas between all the constants aren't required, in which case you may feel free to insert commas unless you're using $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR.)

for easier debugging, you may prefer to always use the commas when not setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll get a fatal compile error rather than a warning. catch it loud, catch it early. πŸ“£

it's not possible to use this module to embed formatting and color attributes using Perl formats. they replace the escape character with a space (as documented in perlform(1)), resulting in garbled output from the unrecognized attribute. even if there were a way around that problem, the format doesn't know that the non-printing escape sequence is zero-length and would incorrectly format the output. for formatted output using color or other attributes, either use sprintf() instead or use formline() and then add the color or other attributes after formatting and before output. that's the move. πŸ’…

πŸ“ NOTES πŸ“

okay so bestie, the codes this module spits out? they're standard terminal control codes β€” like, they comply with ECMA-048 and ISO 6429 (everyone just calls the color ones "ANSI color" fr). and the non-color control codes (bold, dark, italic, underline, and reverse) come from the way older ANSI X3.64 standard for control sequences for video terminals and peripherals. ancient lore πŸ’…

and like… not every display is ISO 6429-compliant, or even X3.64-compliant (some aren't even trying to be 😭). this module will not work as expected on displays that don't honor these escape sequences β€” think cmd.exe, 4nt.exe, and command.com under either Windows NT or Windows 2000. they might just ignore them, or they might display as an ESC character followed by some apparent garbage. either way, it's giving chaos 🫠

Jean Delvare gave us the following table of different common terminal emulators and their support for the various attributes, and other people helped flesh it out. here it is in all its glory, one row at a time πŸ‘‘

  • xterm β€” clear: yes, bold: yes, faint: no, under: yes, blink: yes, reverse: yes, conceal: yes
  • linux β€” clear: yes, bold: yes, faint: yes, under: bold, blink: yes, reverse: yes, conceal: no
  • rxvt β€” clear: yes, bold: yes, faint: no, under: yes, blink: bold/black, reverse: yes, conceal: no
  • dtterm β€” clear: yes, bold: yes, faint: yes, under: yes, blink: reverse, reverse: yes, conceal: yes
  • teraterm β€” clear: yes, bold: reverse, faint: no, under: yes, blink: rev/red, reverse: yes, conceal: no
  • aixterm β€” clear: kinda, bold: normal, faint: no, under: yes, blink: no, reverse: yes, conceal: yes
  • PuTTY β€” clear: yes, bold: color, faint: no, under: yes, blink: no, reverse: yes, conceal: no
  • Windows β€” clear: yes, bold: no, faint: no, under: no, blink: no, reverse: yes, conceal: no
  • Cygwin SSH β€” clear: yes, bold: yes, faint: no, under: color, blink: color, reverse: color, conceal: yes
  • Terminal.app β€” clear: yes, bold: yes, faint: no, under: yes, blink: yes, reverse: yes, conceal: yes

quick glossary so you're not lost: Windows means Windows telnet, Cygwin SSH means the OpenSSH implementation under Cygwin on Windows NT, and Mac Terminal means the Terminal application in Mac OS X. and anywhere the entry is something other than yes or no, that emulator displays the given attribute as something else instead. also!! on an aixterm, clear doesn't reset colors β€” you have to explicitly set the colors back to what you want. 😀 more entries in this table are welcome, so if you got lore, share it 🫢

support for code 3 (italic) is rare and therefore not mentioned in that table. it's not believed to be fully supported by any of the terminals listed, although it's displayed as green in the Linux console β€” but it is reportedly supported by urxvt. slay for urxvt only tbh

and heads up: codes 6 (rapid blink) and 9 (strike-through) are specified in ANSI X3.64 and ECMA-048 but are not commonly supported by most displays and emulators, and therefore they aren't supported by this module either. ECMA-048 also specifies a large number of other attributes, including a sequence of attributes for font changes, Fraktur characters, double-underlining, framing, circling, and overlining. but since none of these attributes are widely supported or useful, they also aren't currently supported by this module. periodt πŸ’…

most modern X terminal emulators support 256 colors. known to not support those colors: aterm, rxvt, Terminal.app, and TTY/VC. rip to them πŸ™ˆ

for info on true color support in various terminal emulators, see True Colour support <https://gist.github.com/XVilka/8346728>. go check your terminal's vibe ✨


πŸ’– AUTHORS πŸ’–

the original idea (using constants) was by Zenin, then Russ Allbery <rra@cpan.org> reimplemented it using subs, and then it got combined with Russ's original idea with input from Zenin. 256-color support is based on work by Kurt Starsinic. Russ Allbery now maintains this module. iconic lineage honestly πŸ‘‘

PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com voice solutions. shoutout 🫢


Copyright 1996-1998, 2000-2002, 2005-2006, 2008-2018, 2020 Russ Allbery <rra@cpan.org>

Copyright 1996 Zenin

Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>

This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.


πŸ‘€ SEE ALSO πŸ‘€

  • the CPAN module Term::ExtendedColor gives you a different and more comprehensive interface for 256-color emulators that might be more convenient. lowkey might be your thing ✨
  • the CPAN module Win32::Console::ANSI provides ANSI color (and other escape sequence) support in the Win32 Console environment.
  • the CPAN module Term::Chrome provides a different interface using objects and operator overloading. ooo fancy πŸŽ€

ECMA-048 is available on-line (at least at the time of this writing) at <https://www.ecma-international.org/publications/standards/Ecma-048.htm>.

ISO 6429 is available from ISO for a charge; the author of this module does not own a copy of it. since the source material for ISO 6429 was ECMA-048 and the latter is available for free, there seems little reason to obtain the ISO standard. save your coins bestie πŸ’Έ

the 256-color control sequences are documented at <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html> (search for 256-color).

info about true color support in various terminal emulators, plus test programs you can run to check the true color support in your own terminal emulator, lives at <https://gist.github.com/XVilka/8346728>.

CLICOLORS <https://bixense.com/clicolors/> and NO_COLOR <https://no-color.org/> are useful standards to be aware of β€” and ideally follow β€” for any application using color. Term::ANSIColor complies with the latter. πŸ’…

the current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/ansicolor/>. it's also part of the Perl core distribution as of 5.6.0. no cap πŸŽ€


that's the whole page bestie, you made it to the end πŸ¦‹ this was Term::ANSIColor(3perl), from perl v5.44.0, dated 2026-10-17 ✨ go color something pretty πŸ’–πŸŒˆ

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms