http://www.perlmonks.org?node_id=1006953

bdalzell has asked for the wisdom of the Perl Monks concerning the following question:

Is there an easy way to use Term::ANSIColor and printf together?

I want to output a formatted response to the terminal.

 printf works fine for this project but the text is monochrome. I would like to be able to highlight some of the text within a line of formatted output

This works but is not elegant:

#!/usr/bin/perl use strict; use Term::ANSIColor qw(:constants); { local $Term::ANSIColor::AUTORESET = 1; print BOLD "Dog record\n"; my $nlabel = BLACK ."Name\:"; my $dogname = RED ."Silkenswift Blaze of Chaos"; my $pt = RED "DC "; my $ft = RED "LCM2 SORC GRC "; my $ot = RED "CD "; printf("%-14s %-41s %-20s \n","$nlabel $pt","$dogname","$ft $ot"); print BLACK ""; print BOLD "################################\n"; }

This is just an example. In the actual program variables are being used in the black text areas such as :

$thisdog{'name'}

Replies are listed 'Best First'.
Re: Term::ANSIColor and printf - easy way to use them together
by tobyink (Canon) on Dec 03, 2012 at 21:38 UTC
    use Term::ANSIColor qw( colored ); printf( "%4s %8s %4s\n", colored('Hello', 'bright_yellow on_magenta'), colored('Hello World', 'white on_blue'), colored('XXX', 'green on_white'), );
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      Thank you so much, that does work!

Re: Term::ANSIColor and printf - easy way to use them together
by johngg (Canon) on Dec 03, 2012 at 23:33 UTC

    Another way using :constants is to either interpolate the BOLD, RED, RESET, whatever into the string using the @{ [ ... ] } construct or make them separate items in the printf with their own %s format specifier. Remember that the constants return ANSI control character sequences that will "take" some of the format width in the first method. That doesn't matter on the first line but would become trickier for the column items of the second line.

    use strict; use warnings; use Term::ANSIColor qw{ :constants }; printf qq{%s\nName:%s%-9s%-41s%s%-14s%s%-6s%s\n}, qq{@{ [ BOLD ] }Dog record@{ [ RESET ] }}, RED, q{DC}, q{Silkenswift Blaze of Chaos}, GREEN, q{LCM2 SORC GRC}, BLUE, q{CD}, RESET;

    I hope this is helpful.

    Cheers,

    JohnGG