在Windows命令提示符下着色Perl输出

问题描述 投票:3回答:1

此问题与以下问题有关:How do I color output text from Perl script on Windows?

但是更具体一些。在某种程度上,我已经可以进行跨平台的着色了:

use Term::ANSIColor;
use Win32::Console;

if (!(-f STDOUT)) {
    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')};
    }
}

但是从字符串内部调用函数时,终端颜色不会立即更改,因此:

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

我想知道是否可以做这样的事情:

    my $print_help = <<PRINT_HELP;
    Usage:  $toolname [-Options] [-fields name1,[name2],...]
    ${\$red->()} toolname version VERSION ${\$reset->()} 
    ${\$blue->()} options: ${\$reset->()}

    PRINT_HELP

    print $print_help;

无色打印。我尝试设置$ | = 1,没有运气。

我没有选择在有问题的系统上安装Win32 :: Console :: ANSI,所以我无法使使用该模块的任何解决方案正常工作。

windows perl cmd colors windows-console
1个回答
0
投票

这种黑客可能符合您的需求。

#!/usr/bin/perl

use warnings;
use strict;

my $alice = sub  { return 'ALICE'; };

my $bob = sub { return 'BOB'; };

my $test = <<'ENDTEST';
lineone
line2 ${\$alice->()} endline
line3 startline ${\$bob->()}
linefour
linefive
ENDTEST

# Add space before newline, split on horizontal whitespace
$test =~ s/\n/ \n/g;
my @testtokens = split /\h/, $test;

# Print '%s ' for each of the testtokens
# Evaluate all testtokens beginning with '$', otherwise print
printf '%s ' x @testtokens, map {$_ =~ /^\$/ ? eval $_ : $_} @testtokens;

获取ENDTEST heredoc并将其打印在最后一行:

$ heretest.pl
lineone 
line2 ALICE endline 
line3 startline BOB 
linefour 
linefive 

也许将按顺序评估事物。

© www.soinside.com 2019 - 2024. All rights reserved.