Home > Software design >  Perl: Display STDOUT and STDERR in different colors on Windows
Perl: Display STDOUT and STDERR in different colors on Windows

Time:08-11

I'm using Perl 5.22.1 with Win32::Console. I have scripts that run make and I thought it would be nice if I could output the errors in red. Win32::Console has handles for stdout and sterr so I thought I could give colors to the individual handles but if I modify stderr, then it also modifies stdout. Is there a way to do this with Win32::Console or another module.

test.pl

use strict;
use warnings;

use Win32::Console;

my $stdout = new Win32::Console(STD_OUTPUT_HANDLE);
my $stderr = new Win32::Console(STD_ERROR_HANDLE);

sub testOutput
{
    print("Testing output\n");
    system("ls error");
    system("ls *.pl");
    print("\n");
}

testOutput();

$stdout->Attr($FG_BLUE);

testOutput();

$stderr->Attr($FG_RED);

testOutput();

$stdout->Write("stdout print\n");
$stderr->Write("stderr print\n");

The output
enter image description here

CodePudding user response:

This happens because regardless of the apparent "stream" on which you invoke Attr, ultimately, both are connected to the console and all Win32::Console does is to output a given sequence of control characters to the console.

If I understand correctly, you want the stderr output of ls to show in one color and the stdout output of ls to show up in another color. In that case, you might want to use Capture::Tiny to capture those streams and output them with the settings you want.

  • Related