2010-03-20 41 views
5

在/ usr/bin中/ env的perl的

use warnings; 
use strict; 

my $text = 'hello ' x 30; 

printf "%-20s : %s\n", 'very important text', $text; 

這個腳本的輸出看起來更礦石較少像這樣:如何在Perl中創建列輸出?

very important text  : hello hello hello hello 
hello hello hello hello hello hello hello hello 
hello hello hello hello hello hello hello hello 
... 

不過,我想這樣的輸出:

very important text: hello hello hello hello 
        hello hello hello hello 
        hello hello hello hello 
        ... 

我忘了提及:文本應該有一個開放的結尾,因爲文本行的右端應該對齊終端的大小。

我怎樣才能改變我的腳本來達到我的目標?

+2

請解釋清楚 – muruga 2010-03-20 08:24:26

+0

你說的是完全有道理的段落?這在終端上既困難又醜陋。我想你從未在CPM上使用過WordStar。 – 2010-03-20 13:05:22

回答

5

您可以使用Text::Wrap

use strict; 
use Text::Wrap; 

my $text = "hello " x 30; 
my $init = ' ' x 20; 
$Text::Wrap::columns = 80; 

print wrap ('', $init, 'very important text : ' . $text); 
+0

文本行的右端應對齊終端的寬度。使用Text :: Wrap我有固定寬度的列。 – 2010-03-20 10:19:51

+1

@sid_com:您可以使用Term :: Size(http://search.cpan.org/~timpx/Term-Size-0.2/Size.pm)獲取終端的列寬,並設置$ Text :: Wrap: :相應的列。 – 2010-03-20 12:26:08

+0

與Dave Sherohman的評論聯繫接受了此答案。 – 2010-03-20 14:12:26

0

雖然我不確定你的問題究竟是什麼格式,你希望你的輸出,我可以告訴你,Perl語言輸出的關鍵是使用格式。

有關如何使用它們來實現幾乎任何輸出格式的入門知識是Perl format primer

+0

我已經瀏覽了一下Perl6 :: Form,但請參閱我對karthi-27的評論 – 2010-03-20 09:26:54

3

試試這個,

use strict; 
use warnings; 

my $text = 'hello ' x 30; 

$text=~s/((\b.+?\b){8})/$1\n      /gs; 
printf "%-20s : %s\n", 'very important text', $text; 
+0

我忘了提及:文本應該有一個開放的結尾,因爲文本行的右端應該對齊終端的大小。 – 2010-03-20 09:23:58

0
#!/usr/bin/env perl 
use warnings; 
use strict; 
use 5.010; 
use Text::Wrap; 
use Term::Size; 

my $text = 'hello ' x 30; 
my $init = ' ' x 22; 
my($columns, $rows) = Term::Size::chars *STDOUT{IO}; 
$Text::Wrap::columns = $columns; 

say wrap ('', $init, 'very important text : ' . $text);