开发者

How can I wrap lines to 45 characters in a Perl program?

I have this text I am writing in a Perl CGI program:

$text = $开发者_如何学编程message;
@lines = split(/\n/, $text);
$lCnt .= $#lines+1;
$lineStart = 80;
$lineHeight = 24;

I want to force a return after 45 characters. How do I do that here?

Thanks in advance for your help.


Look at the core Text::Wrap module:

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";


Check out Text::Wrap. It will do exactly what you need.


Since Text::Wrap for some reason doesn't work for the OP, here is a solution using a regex:

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;

which prints:

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.


The Unicode::LineBreak module can do more sophisticated wrapping of non-English text (Especially East Asian scripts) than Text::Wrap, and has some nice features like optionally being able to recognize URIs and avoid splitting them.

Example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜