Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I color output text from Perl script on Windows?

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.

like image 446
Jesse Vogt Avatar asked Jul 06 '09 14:07

Jesse Vogt


People also ask

How do I print a color text in Perl?

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; .

Which command changes the color of the screen and text?

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.


2 Answers

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";
like image 195
RG boomer Avatar answered Oct 24 '22 20:10

RG boomer


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";
like image 28
lbalazscs Avatar answered Oct 24 '22 19:10

lbalazscs