【问题标题】:Perl printf SpacingPerl printf 间距
【发布时间】:2014-07-31 15:05:17
【问题描述】:

我正在使用 printf 打印 2 列中的数据。第一列最多 12 个字符,但第二列中的数据可能会很长。有没有办法让它从它在换行后的第一行开始的相同缩进开始?

printf("%-12s\t%s", $key, $result);

【问题讨论】:

  • 你能展示一些示例输入和输出吗?
  • Printf 无法做到这一点。您需要将$result 分成 60 个字符的块,将其与键、一些换行符和一些 12 个空格加制表符的字符串放在一起,然后打印出来。

标签: perl printf


【解决方案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.

【讨论】:

    【解决方案2】:

    我不认为 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 之类的东西来做您需要的事情。

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      相关资源
      最近更新 更多