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

Hello monks, I am attempting to print every other line of output in color using Term::ANSIColor and printf. I have managed to sort of pull off what I am trying by the following code

my $c = 0; printf("\n%-7s %-22s %-18s %-35s %-15s %-16s %-30s\n\n", "ID","MAC","I +P","Manufacturer","Authorized","Acknowledged","Notes"); while(@row = $sth->fetchrow_array){ my ($id,$mac,$ip,$man,$auth,$ack,$notes) = @row; push @device_ids, $id; if ($c == 1){ printf( "%-7s %-22s %-18s %-35s %-15s %-16s %-30s\n", colored("$id", 'bold blue on_grey10'), colored("$mac", 'bold blue on_grey10'), colored("$ip", 'bold blue on_grey10'), colored("$man", 'bold blue on_grey10'), colored("$auth", 'bold blue on_grey10'), colored("$ack", 'bold blue on_grey10'), colored("$notes", 'bold blue on_grey10'), ); $c--; } else{ printf("%-7s %-22s %-18s %-35s %-15s %-16s %-30s\n", "$id" +,"$mac","$ip","$man","$auth","$ack","$notes"); $c++; } $cnt++; }

but what seems to happen when I run it is the printf formatting is not applied. I'd like the entire row to be highlighted and formatted not just the individual fields (so the spaces too).

As always, thanks for the help in advanced

  • Comment on Printing alternating lines in color with printf and Term::ANSIColor
  • Download Code

Replies are listed 'Best First'.
Re: Printing alternating lines in color with printf and Term::ANSIColor
by toolic (Bishop) on Oct 06, 2016 at 15:36 UTC
    Format your line before coloring it. This works for me:
    use warnings; use strict; use Term::ANSIColor qw(colored); my $c = 0; my $fmt = '%-7s %-22s %-18s %-35s %-15s %-16s %-30s'; printf "$fmt\n", qw(ID MAC IP Manufacturer Authorized Acknowledged Not +es); for (1..4) { my @row = 1..7; my ($id,$mac,$ip,$man,$auth,$ack,$notes) = @row; my $str = sprintf $fmt, $id,$mac,$ip,$man,$auth,$ack,$notes; if ($c == 1) { print colored($str, 'bold blue on_grey10'), "\n"; $c--; } else{ print "$str\n"; $c++; } }

      Perfect! Thank you, works like a charm