views:

1661

answers:

3

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.

+13  A: 

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. :-)

cdleary
See also http://search.cpan.org/~jlmorel/Win32-Console-ANSI-1.04/lib/Win32/Console/ANSI.pm
Hasturkun
I messed around with just using Term::ANSIColor but it was only printing the escape sequences...not properly showing the colors. I downloaded and built the package suggested by Hasturkun (http://search.cpan.org/~jlmorel/Win32-Console-ANSI-1.04/) and everything started working. Thanks!
Jesse
+6  A: 

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
mphuie
A: 
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