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 wou
Win32::Console - here's an example
use Win32::Console;
my $CONSOLE = Win32::Console->new(STD_OUTPUT_HANDLE);
my $attr = $CONSOLE->Attr(); # Get current console colors
$CONSOLE->Attr($FG_YELLOW | $BG_GREEN); # Yellow text on green
print "This is a test\n";
$CONSOLE->Attr($attr); # Set console colors back to original
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";
For any terminal that supports ANSI escape codes you can use the Term::ANSIColor package available on CPAN.
From the Wikipedia page:
Console windows in Windows versions based on NT (Windows NT 4.0, Windows 2000, Windows XP, Windows Server 2003, Windows Vista and Windows Server 2008) do not natively support ANSI Escape sequences, though some support is possible.
Don't know any more Windows-specific information than that, I'm a POSIX guy. :-)
system("color A"); #DOS command, change text color to lime
system("color 7"); #DOS command, change text color to white
However those commands change text color on the whole screen. Type "color ?" in DOS window to see color options
I am using strawberry perl on Windows and I did not have Win32::Console package. To install this package type in console:
perl -MCPAN -e shell
install Win32::Console
exit