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

后端 未结 5 1010
别那么骄傲
别那么骄傲 2021-02-06 00:36

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

5条回答
  •  甜味超标
    2021-02-06 00:59

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

提交回复
热议问题