• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
沈庆伟心理咨询
咨询微信:xlzxs-sqw
博客园    首页    新随笔       管理     

Perl 输出颜色

对于Linux管理员来说,grep是日常最常用的命令,可以把匹配的字符输出,同样可以输出颜色。

# grep --color 'test' /var/log/maillog

无聊练功:用perl 实现grep --color

# vi colorgrep

#!/usr/bin/perl
use Term::ANSIColor;
my $test;
if (@ARGV != 2){
die "Please use (colorgrep 'some key word' filename)\n";
}
$test = shift @ARGV;
while(<>){
if(/$test/i){
print "$`";
print color "bold red";
print "$&";
print color 'reset';
print "$'";
}
}

这里调用了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

还有以下的简化使用方法

2) 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

等。

例如:
print BOLD BLUE ON_WHITE “Text”, RESET, “\n”;

如果你打印完之后想清除掉字符串的格式,一定要记得在最后加上一个RESET的属性值。
例如:

use Term::ANSIColor qw(:constants);
print BOLD, BLUE, “This text is in bold blue.\n”, RESET;

3) $Term::ANSIColor::AUTORESET = 1;

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

看一个完整的例子:

use Term::ANSIColor qw(:constants);
$Term::ANSIColor::AUTORESET = 1;
print BOLD BLUE “This text is in bold blue.\n”;
print “This text is normal.\n”;

这三种方法,使用起来各有千秋,可根据要打印的复杂程度选用。

http://www.ahbank.org/
posted @ 2012-02-29 11:29  沈庆伟心理咨询  阅读(1733)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3