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?
If you prefer, or if there is any possibility that the fields may
themselves contain spaces, you can build an array of maximum field
widths and use a bespoke pad subroutine.
Rob
use strict;
use warnings;
use List::Util 'max';
my @data = (
[qw/ abc 12 4567 /],
[qw/ xy4z xtr4 sdf /],
[qw/ PQRSDR xcvf scc234 /],
);
my @widths;
for my $i (0.. $#{$data[0]}) {
push @widths, max map length($_->[$i]), @data;
}
for my $row (@data) {
my $line;
$line .= pad($row->[$_], 1+$widths[$_]) for 0 .. $#$row-1;
$line .= $row->[-1];
print $line, "\n";
}
sub pad {
my ($string, $length) = @_;
for ($length - length $string) {
$string .= '_' x $_ if $_ > 0;
}
$string;
}
**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/