I wanted to add a little color to a command-line program, to highlight a few things. Windows NT/2k/XP doesn't have ANSI X3.64 control codes in the console window.

So, I played around with the Win32::Console module. Setting the current attribute will affect subsequent output, even if they come through layers of file stuff first. The secret is to make sure you flush before changing it again.

Rather than using the Console::Write function, I use ordinary print so that it still works if the output is redirected to a file. The changing attribute of the console window is simply ignored, and the same text is printed anyway.

use strict; use warnings; use IO::Handle; use Win32::Console; my $CONSOLE = new Win32::Console(STD_OUTPUT_HANDLE); my $save_attr= $CONSOLE->Attr; my $caption_attr= 10; # bright green on black sub print_color ($@) { my $color= shift; STDOUT->flush(); $CONSOLE->Attr ($color); print @_; STDOUT->flush(); $CONSOLE->Attr ($save_attr); } print_color ($caption_attr, "Hello ", 42, " world.\n");

In reply to color text output in Windows by John M. Dlugosz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.