ANSI Colors and Perl

This week I came across an article about ANSI colors on Perl Weekly.
While this article nicely explains ANSI colors and how you can use them, I usually go in a different direction when I want to use them, see below.
And by the way, you can use
less -r
to interpret escape sequences, so you can see everything colorized in less as well.

Hackish way

When I don't have access to CPAN easily (need to run a quick script on a host in a DMZ and software maintenance is a nightmare), I grab colors which can be sourced from any sh compatible shell and sets variables that can be used. However, in Perl, that won't work 1:1, so I do something like this:
 1 #!/usr/bin/perl
 2 use strict;
 3 use warnings;
 4 my $colormap = readcolors();
 5 print $colormap->{red_on_black} . "Hello, World!" . $colormap->{color_reset} . "\n";
 6 # pick your color from the map's keys
 7 
 8 sub readcolors {
 9    my $result ={};
10    open(my $IN, "<", "/path/to/colors") or die "Can't open colors file for reading!";
11    while (my $line = <$IN>) {
12       chomp($line);
13       # skip empty lines
14       next unless $line =~ m/=/;
15       my ($k, $v) = split /=/, $line;
16       $v =~ s/"//g;
17       $result->{$k} = $v;
18    }
19    close($IN);
20    return $result;
21 }
22 

The clean solution

There's always a module on CPAN, so rewriting the example from Gabor's article:
 1 #!/usr/bin/perl
 2 use strict;
 3 use warnings;
 4 use feature 'say';
 5 use Term::ANSIColor;
 6 
 7 my $black   = color("black");
 8 my $red     = color("red");
 9 my $green   = color("green");
10 my $yellow  = color("yellow");
11 my $white   = color("white");
12 my $nocolor = color("reset");
13 
14 say("Plain text in the default color");
15 say($green);
16 say("Green text");
17 say($red);
18 say("Red text");
19 say("$yellow yellow $green green $red red");
20 say($white);
21 say("White text");
22 say($black);
23 say("Black text");