On 03/04/2013 11:22 AM, Chris Stinemetz wrote:
I would like to pass a list of variables to printf.

Is there a way to multiply a set printf length instead of
righting typing printf for each variable?

what I am trying to do is below:

          printf "%-${longest}s x 27\n",

  
$rptType,$mkt,$timeStamp,$cell,$sector,$carr,$satt,$sest,$fit,$psEst,$catt,$cest,$pcEst,$rfLost,

  
$cpDropCell,$cpDropRnc,$tuneAway,$tDrops,$pDcr,$ia,$pIa,$tccf,$failAp,$failTp,$failA10,$failAAA,$failPDSN;

Thank you,

Chris

Chris,

You can use the '*' length specifier to do what you are wanting to do.. If you set '$longest' to the longest length, then this should do the trick:

printf("%-*s\n", $longest, $string);

Unfortunately, that only gets you one string out. Using the printf in this way would require you to repeat the length ahead of each variable if you want to print them all at one time, with one printf call. There are further "printf tricks" that would allow you to specify the length only once, but they get sort of ugly (IMHO). If I were doing this,
I think that I would do something like:

my @vals2print;
my $longest;
foreach my $val ($rptType,$mkt,$timeStamp,$cell,$sector,$carr,$satt,$sest,$fit,$psEst,$catt,$cest,$pcEst,$rfLost, $cpDropCell,$cpDropRnc,$tuneAway,$tDrops,$pDcr,$ia,$pIa,$tccf,$failAp,$failTp,$failA10,$failAAA,$failPDSN) {
  push @vals2print, $val;
  $longest = ($val > $longest) ? $val : $longest;
}
printf("%-*s ",$longest, $_) foreach @vals2print;
print "\n";

It might be more efficient to just generate the format string programmatically, and only make one printf call:

my @vals2print;
my $longest;
foreach my $val ($rptType,$mkt,$timeStamp,$cell,$sector,$carr,$satt,$sest,$fit,$psEst,$catt,$cest,$pcEst,$rfLost, $cpDropCell,$cpDropRnc,$tuneAway,$tDrops,$pDcr,$ia,$pIa,$tccf,$failAp,$failTp,$failA10,$failAAA,$failPDSN) {
  push @vals2print, $longest;
  $longest = ($val > $longest) ? $val : $longest;
}
my $pf_format = "%-" . $longest . "s ";
$pf_format = $pf_format x scalar @vals2print;
$pf_format .= "\n";
printf($pf_format, @vals2print);


Note: I just typed that up without testing, so caveat scriptor. Hopefully the ideas come across, at least.

Nathan


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to