如何在Perl程序中将行换行为45个字符?

时间:2010-10-14 18:44:56

标签: perl

我有这个文本我在Perl CGI程序中写道:

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

我想在45个字符后强制返回。我怎么在这里做到这一点?

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:13)

查看核心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";

答案 1 :(得分:1)

结帐Text::Wrap。它将完全满足您的需求。

答案 2 :(得分: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 :(得分:0)

Text::Wrap 相比,Unicode::LineBreak 模块可以对非英语文本(尤其是东亚文字)进行更复杂的包装,并且具有一些不错的功能,例如可选择识别 URI 并避免拆分它们。

示例:

#!/usr/bin/env perl
use warnings;
use strict;
use Unicode::LineBreak;

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 $wrapper = Unicode::LineBreak->new(ColMax => 45, Format => "NEWLINE");
print for $wrapper->break($longstring);