如何在Perl中格式化输出?

如何在Perl中格式化输出?,perl,text,formatting,Perl,Text,Formatting,我有一个负责格式化输出的Perl代码。问题是,我需要计算出每个字符串中一个特定字符之前要放置的制表符的正确数量(假设它是/)。因此,我不希望得到不同长度的行,而是希望得到固定长度的字符串(但尽可能短,使用最大长度)。我应该如何处理这个问题 输出示例(格式已注释掉,仅为原始数组): 我需要这样: title with some looong words / short text Different title / another short text 这是我第一次尝试,

我有一个负责格式化输出的Perl代码。问题是,我需要计算出每个字符串中一个特定字符之前要放置的制表符的正确数量(假设它是/)。因此,我不希望得到不同长度的行,而是希望得到固定长度的字符串(但尽可能短,使用最大长度)。我应该如何处理这个问题

输出示例(格式已注释掉,仅为原始数组):

我需要这样:

title with some looong words / short text
Different title              / another short text
这是我第一次尝试,但它不涉及在一个特定字符后使用制表符

my $text = Text::Format->new;

$text->rightAlign(1);
$text->columns(65);
$text->tabstop(4);

$values[$i] = $text->format(@values[$i]);
该模块可能会对您有所帮助

#!/usr/bin/perl
use warnings;
use strict;

use Text::Table;

my @array = ('Long title with some looong words', 'short text',
             'Another title',                     'another short text');

my $table = Text::Table::->new(q(), \' / ', q()); # Define the separator.
$table->add(shift @array, shift @array) while @array;
print $table;

从文档中可以找到,Text::Format仅用于段落格式设置。您需要的是表格格式。基本方法是将数据拆分为每行和每列的文本矩阵,找到每列的最长元素,并使用该元素输出固定宽度的数据。e、 g:

my @values = (
    'Long title with some looong words / short text',
    'Another title / another short text',
);

# split values into per-column text
my @text = map { [ split '\s*(/)\s*', $_ ] } @values;

# find the maximum width of each column
my @width;
foreach my $line (@text) {
    for my $i (0 .. $#$line) {
        no warnings 'uninitialized';
        my $l = length $line->[$i];
        $width[$i] = $l if $l > $width[$i];
    }
}

# build a format string using column widths
my $format = join ' ', map { "%-${_}s" } @width;
$format .= "\n";

# print output in columns
printf $format, @$_ foreach @text;
这将产生以下结果:

Long title with some looong words / short text        
Another title                     / another short text

在Perl中,有两种普遍接受的文本格式设置方法,因此列排列整齐:

  • 使用
    printf
    sprintf
    。这可能是最常见的方法
  • 使用功能。定义一行的外观,然后使用该格式打印
我已经多年没有看到人们使用Perl格式规范了。在Perl3.x鼎盛时期,它是一个很大的特性,因为Perl主要用作超级awk替换语言(实用提取和报告语言)。然而,机制仍然存在,我相信学习会很有趣


现在是查询的第二部分。你真的不只是想格式化文本,你还想用制表符格式化文本

幸运的是,Perl有一个名为的内置模块。这是一个模块,它可以完成一两个模糊的任务,但做得很好

实际上,
Text::Tabs
并不能很好地处理这两项任务,但已经足够了

使用
sprintf
或内置的Perl格式化功能生成报告。将整个报告保存在一个数组中。它必须是一个数组,因为
Text::Tabs
不处理NLs。然后使用
unexpand
函数将该数组中的空格替换为另一个带有制表符的数组


WORD'O警告
Text::Tabs
做了一些非常不正常的事情:它未经您的许可将变量
$tabstop
导入到您的程序中。如果使用名为
$tabstop
的变量,则必须对其进行更改。您可以将
$tabstop
设置为选项卡所代表的空间数。默认设置为8。

1。迭代所有字符串以找到最大长度2。在其他字符串中插入制表符以匹配以前找到的最大长度3?4.利润请添加一些示例数据。很难理解你想做什么。
Long title with some looong words / short text        
Another title                     / another short text