我有一个问题,当我使用彩色文本时,printf格式(对齐)不正确。 在此示例中,请注意最后一列的左侧是1个空格。 搜索解决方案只会告诉我,它很可能与代码中颜色变量中的转义序列有关。
有一个解决此问题的简单方法,还是我需要添加代码以在文本着色时添加一个空格?
代码:
#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use Data::Dumper;
# Color variables
my $DEFAULTCOLOR = "\e[0m";
my $RED = "\e[31m";
my $GREEN = "\e[32m";
my $YELLOW = "\e[33m";
my $BLUE = "\e[34m";
my $MAGENTA = "\e[35m";
my %HeartbeatHash = (
'BOTH' => [ '-', 0, '-', 10 ],
'PTN' => [ '-', 0, '-', 10 ],
'PKT' => [ '-', 0, '-', 10 ],
);
printf ("%-9s %7s %-7s %-s\n", "Heartbeat", "Counter", "LastRun", "TriggerTime");
printf ("%-9s %7s %-7s %-d\n", "NOCOLOR", ${HeartbeatHash{'PKT'}[1]}, ${HeartbeatHash{'PKT'}[2]}, ${HeartbeatHash{'PKT'}[3]});
${HeartbeatHash{'PKT'}[1]}++;
${HeartbeatHash{'PKT'}[2]} = "Passed";
printf ("%-9s %7s %-7s %-s\n", "Heartbeat", "Counter", "LastRun", "TriggerTime");
printf ("%-9s %7s %-7s %-d\n", "NOCOLOR", ${HeartbeatHash{'PKT'}[1]}, ${HeartbeatHash{'PKT'}[2]}, ${HeartbeatHash{'PKT'}[3]});
${HeartbeatHash{'PKT'}[1]}++;
${HeartbeatHash{'PKT'}[2]} = "${GREEN}Passed${DEFAULTCOLOR}";
printf ("%-9s %7s %-7s %-s\n", "Heartbeat", "Counter", "LastRun", "TriggerTime");
printf ("%-9s %7s %-7s %-d\n", "GREEN", ${HeartbeatHash{'PKT'}[1]}, ${HeartbeatHash{'PKT'}[2]}, ${HeartbeatHash{'PKT'}[3]});
$DEFAULTCOLOR = "\033[0m";
$GREEN = "\033[32m";
${HeartbeatHash{'PKT'}[1]}++;
${HeartbeatHash{'PKT'}[2]} = "${GREEN}Passed${DEFAULTCOLOR}";
printf ("%-9s %7s %-7s %-s\n", "Heartbeat", "Counter", "LastRun", "TriggerTime");
printf ("%-9s %7s %-7s %-d\n", "GREEN", ${HeartbeatHash{'PKT'}[1]}, ${HeartbeatHash{'PKT'}[2]}, ${HeartbeatHash{'PKT'}[3]});
输出(终端在最后两行中以绿色显示文本“ Passed”:
Heartbeat Counter LastRun TriggerTime
NOCOLOR 0 - 10
Heartbeat Counter LastRun TriggerTime
NOCOLOR 1 Passed 10
Heartbeat Counter LastRun TriggerTime
GREEN 2 Passed 10
Heartbeat Counter LastRun TriggerTime
GREEN 3 Passed 10
答案 0 :(得分:3)
分别打印颜色代码,以使printf
不会将它们包括在长度计算中:
my @heartbeats = (
{ color => 'GREEN',
code_before => "",
code_after => "",
counter => 1,
last_run => 'Passed',
time => 10 },
{ color => 'GREEN',
code_before => $GREEN,
code_after => $DEFAULTCOLOR,
counter => 2,
last_run => 'Passed',
time => 10 },
);
printf "%-9s %7s %-7s %-s\n", qw( Heartbeat Counter LastRun TriggerTime );
for my $heartbeat (@heartbeats) {
printf "%-9s %7s %s%-7s%s %-d\n",
@$heartbeat{qw{ color counter code_before last_run code_after time }};
}
此外,使用Term::ANSIColor可以简化代码并防止ANSI颜色序列中的意外错字。