开发者

How can I get colored output with printf and Perl's Term::ANSIColor?

is there a way to get wit开发者_JS百科h printf colored output?

#!/usr/bin/perl
use warnings; 
use strict;
use Term::ANSIColor;

printf "%4.4s\n", colored( '0123456789', 'magenta' );

Output: (only newline)


I assume you want something like the following:

#!/usr/bin/perl
use warnings;
use strict;
use Term::ANSIColor;

print colored( sprintf("%4.4s", '0123456789'), 'magenta' ), "\n";


You need to change your code like the following

printf "%s\n", colored( '0123456789', 'magenta' );

Because we can't get the first 4 character in the string. If you give the string value to the printf function it will print the value up to null character. We can't get the first 4 characters.


The problem is "%4.4s\n" try "%s\n" it will work. the reason is that colors are chars (escape chars) and you are cutting them. try printf "%s\n", length(colored( '0123456789', 'green' )); to understand better.


The simplest way to print colored output can be

use Term::ANSIColor qw(:constants);
print RED, "Stop!\n", RESET;
print GREEN, "Go!\n", RESET;


If you want to use colors in print do the folowing:

use Term::ANSIColor qw(:constants);

And then use the specific colors names.

For example: If you want to print text in green bold color, use: print GREEN BOLD "Passed", RESET;.

The RESET resets the color back to normal.

If you want to print text in red blinking color, use: print BLINK BOLD RED "Failed!", RESET;

If you want to display a progress bar for example using a green "box", use: print ON_GREEN " ", RESET;

Another twik: if you want to reposition the cursor accross the screen, use: print "\033[X;YH"; where X is line pos and Y is column pos, for exmple: print "\033[5;7H";


This is a solution to preserve the space alignment when print multiple value (eg. from DB):

print sprintf("%-10s %-32s %-10s\n",
  $row->{id},
  $row->{name},
  ($row->{enabled} ? colored(sprintf("%-10s", 'Enabled'), 'GREEN') : 'Disabled'),
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜