ETOOBUSY 🚀 minimal blogging for the impatient
Term::ANSIColor and (lack of) the terminal
TL;DR
A little note on Term::ANSIColor.
Sometime it’s handy to spice up the terminal output with some color, e.g. to underline some important part. Doing this has been super-easy since a long time in Perl, thanks to the core module Term::ANSIColor:
use Term::ANSIColor ':constants';
say BOLD, BLUE, 'wha',
RED, 'tev',
GREEN, 'ah!';
say RESET, '(back...)';
This is implemented by interspersing escape sequences in the output, that are intercepted by the terminal application to e.g. change to bold or switch to a different color.
While useful, this can be detrimental when you look for data (e.g. with
grep
), because escape sequences will get in the way. For example,
this:
$ ./ta.pl | grep whatevah
produces no output:
We need the escape sequences to be disabled when the output is not to a
terminal… which is what the -t
test function helps us doing! So we
can do this (order is important, put it before loading Term::ANSIColor!):
BEGIN{ $ENV{ANSI_COLORS_DISABLED} = 1 unless -t STDOUT }
use Term::ANSIColor ':constants';
say BOLD, BLUE, 'wha',
RED, 'tev',
GREEN, 'ah!';
say RESET, '(back...)';
Setting environment variable ANSI_COLORS_DISABLED
to a true vaue
before loading the module (note the BEGIN
block) puts the module in
quiet mode and everything works as expected:
Or… just use Term::ANSIColor::Conditional from CPAN 🤫