Perl: ANSI colors

Perl's Term::ANSIColor is good but sometime it's overkill. I wrote a function to change colors before your print.

$color = color("13_on_5");
$reset = color("reset");

print $color . "Pink on purple" . $reset . "\n";
# String format: '115', '165bold', '10_on_140', 'reset', 'on_173'
sub color {
    my $str = shift();

    # If we're NOT connected to a an interactive terminal don't do color
    if (-t STDOUT == 0) { return ''; }

    # No string sent in, so we just reset
    if (!$str || $str eq 'reset') {
        return "\e[0m";
    }

    # Get foreground and bold
    my ($fc,$bold) = $str =~ /^(\d+)(b|bold)?/g;
    # Get the background color (if present)
    my ($bc)       = $str =~ /on_?(\d+)$/g;

    my $ret = '';
    if ($bold) { $ret .= "\e[1m"; }
    if ($fc)   { $ret .= "\e[38;5;${fc}m"; }
    if ($bc)   { $ret .= "\e[48;5;${bc}m"; }

    return $ret;
}

The ANSI color numbers can be determined using term-colors.pl.

Note: You can test if you're outputting to a TTY which supports ANSI colors, or a file using the -t test.

sub is_tty {
    return -t STDOUT;
}

See also: Regexp to check for ANSI color codes

Leave A Reply
All content licensed under the Creative Commons License