2010-10-14 18 views
3

我有這樣的文字,我在一個Perl CGI程序編寫:如何在Perl程序中將行換行爲45個字符?

$text = $message; 
@lines = split(/\n/, $text); 
$lCnt .= $#lines+1; 
$lineStart = 80; 
$lineHeight = 24; 

我想生效後45個字符的回報。我該怎麼做?

在此先感謝您的幫助。

+0

可能重複的[我怎麼可以用Perl包裝一個字符串?](http://stackoverflow.com/ques tions/956379/how-can-i-word-wrap-a-string-in-perl) – Ether 2010-10-18 17:18:39

回答

1

結賬Text::Wrap。它將完全符合你的需求。

+0

Text :: Wrap在這裏似乎不起作用。 – seeker7805 2010-10-14 20:14:10

+2

請參閱[如何解決我的Perl CGI程序](http://stackoverflow.com/q/2165022/8817)。 – 2010-10-14 21:21:19

12

看核心Text::Wrap模塊:

use Text::Wrap; 
my $longstring = "this is a long string that I want to wrap it goes on forever and ever and ever and ever and ever"; 
$Text::Wrap::columns = 45; 
print wrap('', '', $longstring) . "\n"; 
+0

謝謝。很抱歉,當我這樣做時,我收到了內部服務器錯誤消息。 – seeker7805 2010-10-14 20:13:40

+4

你得到一個500內部服務器錯誤是你的問題。它沒有使答案更加正確。 – 2010-10-14 21:22:38

+3

請參閱[如何解決我的Perl CGI程序](http://stackoverflow.com/q/2165022/8817)。 – 2010-10-14 21:42:34

1

由於Text::Wrap某種原因OP不起作用,這裏是使用正則表達式的解決方案:

my $longstring = "lots of text to wrap, and some more text, and more " 
       . "still. thats right, even more. lots of text to wrap, " 
       . "and some more text."; 

my $wrap_at = 45; 

(my $wrapped = $longstring) =~ s/(.{0,$wrap_at}(?:\s|$))/$1\n/g; 

print $wrapped; 

它打印:

lots of text to wrap, and some more text, and 
more still. thats right, even more. lots of 
text to wrap, and some more text. 
+3

需要考慮幾個邊緣案例:(1)如果你有一串超過45個字母而沒有空格,會發生什麼? (2)給定一系列跨越邊界的空間,位置45處的空間應該位於新行的開始位置還是舊行的末尾,還是完全放棄? – Jander 2010-10-15 03:06:18

相關問題