在Perl中使用Term::ANSIColor模块控制颜色的三种方法

  • 方法一

Term::ANSIColor的函数color有以下参数:
clear, reset, dark, bold, underline, underscore, blink, reverse, concealed, black, red, green, yellow, blue, magenta, cyan, white, on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, and on_white

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/perl
 
use Term::ANSIColor;
 
print color "red";
print "REDn";
print color "green";
print "GREENn";
print color "bold blue";
print "BOLD BLUEn";
print color "on_yellow";
print "ON YELLOWn";
print color "on_cyan";
print "ON CYANn";
print color "reset";

  • 方法二

1
use Term::ANSIColor qw(:constants);

使用这种方法时,可以直接把颜色属性放在要输出的问题前面,从而简化输出步骤。颜色属性有:
CLEAR, RESET, BOLD, DARK, UNDERLINE, UNDERSCORE, BLINK, REVERSE, CONCEALED, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, ON_BLACK, ON_RED, ON_GREEN, ON_YELLOW, ON_BLUE, ON_MAGENTA, ON_CYAN, and ON_WHITE
打印完之后想清除掉字符串的格式,一定要记得在最后加上一个RESET的属性值。

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/perl
 
use Term::ANSIColor qw(:constants);
 
print BOLD BLUE ON_WHITE "This text is in bold blue on white.n", RESET;
print "This text is normal.nn";
 
print BOLD BLUE ON_WHITE "This text is in bold blue on white.n";
print "This text is normal???nn";
 
print RESET;
print "This text is normal!nn";
  • 方法三

对于方法二,如果不想在每条打印语句后面加上RESET的话,可以直接把$Term::ANSIColor::AUTORESET的值设为true。这样每次打印完字符,只要属性值之间没有逗号,系统将自动清除颜色属性。

1
2
3
4
5
6
7
#!/usr/bin/perl
 
use Term::ANSIColor qw(:constants);
$Term::ANSIColor::AUTORESET = 1;
 
print BOLD BLUE ON_WHITE "This text is in bold blue on white.n";
print "This text is normal.n";