I would like to color format the text printed to the console using the Perl print command.
In my case the script will only be run under WinXP-DOS Command Line but it would be great if it was OS independent although I would rather tie it to WinXP than have to download a seperate package.
If you want to use colors in print do the folowing: use Term::ANSIColor qw(:constants); And then use the specific colors names. For example: If you want to print text in green bold color, use: print GREEN BOLD "Passed", RESET; .
The color command allows users running MS-DOS or the Windows command line to change the default color of the background or text. To change the window text color, see: How to change font, layout, and color options in command line.
building off of mphuie's Example, making it more cross-platform:
use Term::ANSIColor;
use Win32::Console;
if ($^O =~ /win/) {
our $FG_BLUE;
our $FG_YELLOW;
our $FG_RED;
our $BG_GREEN;
my $CONSOLE = Win32::Console->new(STD_OUTPUT_HANDLE);
my $attr = $CONSOLE->Attr(); # Get current console colors
$blue = sub {$CONSOLE->Attr($FG_BLUE);return};
$reset = sub {$CONSOLE->Attr($attr);return};
$yellow = sub {$CONSOLE->Attr($FG_YELLOW);return};
$red = sub {$CONSOLE->Attr($FG_RED);return};
} else {
$blue = sub {return color('bold blue')};
$reset = sub {return color('reset')};
$yellow = sub {return color('yellow')};
$red = sub {return color('red')};
}
Quick note though: The Terminal colors do not change immediately when the functions are called from inside strings, thus:
print "${\$blue->()} this is blue\n";
print "${\$blue->()}This is... not blue${\$reset->()}\n";
print "this is Blue ${\$blue->()}\n";
print "this is reset${\$reset->()}\n";
Here is what worked best for me after all:
1) Installed Win32::Console::ANSI (note that this is not the same as Win32::Console)
perl -MCPAN -e shell
cpan> install Win32::Console::ANSI
2) If this module is loaded before Term::ANSIColor, you can use the standard Term::ANSIColor API and it actually works (I tried it with Windows 7).
use Win32::Console::ANSI;
use Term::ANSIColor;
print color("blue"), "blue\n", color("reset");
print "normal\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With