Donoru
Donoru

Reputation: 155

How can you change text color in Perl?

I need to find a simple way to change the color of output text in Perl. How do I do it?

print "Do you agree with me that I'm a Perl noob?";
print "> ";
chomp(my $question = <STDIN>);
if($question eq "yes") {
  print "You are smart!";
} if($question eq "no") {
  print "You stupid";
}

I just want to change the color. Nothing else to say.

Upvotes: 0

Views: 2524

Answers (1)

daxim
daxim

Reputation: 39158

Windows part untested:

use if 'MSWin32' eq $^O, 'Win32::Console::ANSI';
use Term::ANSIColor qw(:constants);

print BRIGHT_RED ON_BLUE "You are smart!\n";
print BOLD GREEN ON_WHITE "You stupid\n";

END { print RESET; }

If the terminal gets messed up because the END block was not run (e.g. due to a crash), run the reset command from ncurses-utils package.

Unfortunately Term::ANSIColor does not support arbitrary colours because the API is stuck in the last millenium. You need to speak raw ANSI codes.

for my $c (split //, 'Sunshine, lollipops and rainbows') {
    printf "\x1b[38;2;%d;%d;%dm", rand 256, rand 256, rand 256; # fg
    printf "\x1b[48;2;%d;%d;%dm", rand 256, rand 256, rand 256; # bg
    print $c;
}
END { print "\x1b[0m"; } # reset

Upvotes: 4

Related Questions