2012-11-07 109 views
2

我有一個負責格式化輸出的Perl代碼。問題是我需要計算在每個字符串中的一個特定字符之前放置正確數量的選項卡(假設它是/)。因此,我不想獲得不同長度的線,而是希望獲得固定長度的字符串(但儘可能短,使用最長的字符串)。我應該如何處理這個問題?輸出如何在Perl中格式化輸出?

實例(與格式註釋掉,只是原始陣列):

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

我需要這樣的:

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]); 
+0

1.迭代所有字符串以查找最大長度2.將製表符插入其他字符串以匹配先前找到的最大長度3 ...? 4.利潤 – m0skit0

+0

請添加一些示例數據。很難理解你想要做什麼。 – simbabque

回答

1

通常有兩種方式接受格式化在Perl中文字,所以列排隊:

  • 使用printfsprintf。這可能是最常見的方式。
  • 使用Perl Format功能。您可以定義您想要的行的樣式,然後使用write打印到該格式。

我還沒有看到人們多年來使用Perl格式規範的東西。這是在Perl 3.x的全盛時期一大特色回來,因爲Perl中主要用作超AWK更換語言(P ractical Ë xtraction和[R eporting 大號 anguage)。然而,這個機制仍然存在,我相信學習會很有趣。


現在來查詢的第二部分。你真的不僅僅希望文本被格式化,你希望它是格式化的標籤

幸運的是,Perl有一個名爲Text::Tabs的內置模塊。它是執行一兩個模糊任務的模塊之一,但是它們很好。

實際上,Text::Tabs並沒有處理好它的兩個任務,但是沒有足夠的。

使用sprintf或使用Perl格式化功能構建報告。將整個報告保存在一個數組中。它必須是一個數組,因爲Text::Tabs不處理NL。然後使用unexpand函數將該數組中的空格替換爲帶有製表符的另一個數組。

WORD「O警告Text::Tabs做了很調皮:它進口的可變$tabstop到你的程序,而不徵求您的同意。如果您使用名爲$tabstop的變量,則必須更改它。您可以將$tabstop設置爲選項卡所代表的空格數。它默認設置爲8。

0

模塊Text::Table可以幫助你。

#!/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; 
0

從我可以在文檔的文本::格式找到只做段落格式。你想要的是一種表格格式。其基本方法是將數據拆分爲每行&列的文本矩陣,找到每列最長的元素,然後使用它輸出固定寬度的數據。例如: -

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