我使用printf打印出2列数据。第一列最多12个字符,但第二列中的数据可能会很长。有没有办法让它从它在换行后第一行开始的相同缩进开始?
printf("%-12s\t%s", $key, $result);
答案 0 :(得分:1)
我不认为printf本身可以做你想做的事,但你可以自己做包装。以下示例是原始的但可用:
sub wrap {
my ($str, $first_col_size, $max_col_size) = @_;
my $ret = $str;
$ret =~ s/(.{$max_col_size})/"$1\n" . (' ' x $first_col_size) . "\t"/ge;
$ret;
}
printf("%-12s\t%s\n", $key, wrap($result, 12, 60));
或许您可以使用Text::ASCIITable on CPAN之类的东西来做您需要的事情。
答案 1 :(得分:1)
我建议您使用核心库Text::Wrap
。
以下内容将实现您所说的内容:
use strict;
use warnings;
use Text::Wrap;
local $Text::Wrap::columns = 72;
while (<DATA>) {
my ($word, $paragraph) = split ' ', $_, 2;
print wrap(sprintf("%-12s", $word), ' 'x12, $paragraph), "\n";
}
__DATA__
one The fallen python hurts behind your entering delight. A leader defects within the birth! The torture overflows? The verdict beams behind the energy.
two A convinced undergraduate seasons the bonus. The present alert mends inside the gesture. How will the publicized coordinate swallow a log panic?
three A tourist faints? An alive biography behaves on top of a grief. A storm scares a conductor throughout an anxious initiate.
输出:
one The fallen python hurts behind your entering delight. A
leader defects within the birth! The torture overflows?
The verdict beams behind the energy.
two A convinced undergraduate seasons the bonus. The present
alert mends inside the gesture. How will the publicized
coordinate swallow a log panic?
three A tourist faints? An alive biography behaves on top of a
grief. A storm scares a conductor throughout an anxious
initiate.