On 28/09/2013 06:59, Rajeev Prasad wrote:
hello,
following is obtained by concatenating 3 values using an underscore to
produce a list:
|abc_12_4567
xy4z_xtr4_sdf
PQRSDR_xcvf_scc234|
i want them to look neat, something like this: where they look in line.
I do not know before hand how long each word would be....
|abc____12____4567
xy4z___xtr4__sdf
PQRSDR_xcvf__scc234|
how could i use the sprintf to obtain such an effect?
You could build a format into a separate variable, using the maximum
length of each column as the field size.
Because sprintf will pad only with spaces (or zeroes) you need to
transliterate once the lines are built.
This program demonstrates. Note that the statement modifier
for 1 + max map length($_->[$i]), @data;
doesn't loop at all: it just serves to contextualize the calculation
into $_.
Rob
use strict;
use warnings;
use List::Util 'max';
my @data = (
[qw/ abc 12 4567 /],
[qw/ xy4z xtr4 sdf /],
[qw/ PQRSDR xcvf scc234 /],
);
my $format;
for my $i (0.. $#{$data[0]}-1) {
$format .= "%-${_}s" for 1 + max map length($_->[$i]), @data;
}
$format .= "%s\n";
for my $row (@data) {
(my $line = sprintf $format, @$row) =~ tr/ /_/;
print $line;
}
**output**
abc____12___4567
xy4z___xtr4_sdf
PQRSDR_xcvf_scc234
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/