tags:

views:

88

answers:

3

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.

+1  A: 

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

Cfreak
Text::Wrap does not seem to be working here.
seeker7805
See [How do I troubleshoot my Perl CGI program](http://stackoverflow.com/q/2165022/8817).
brian d foy
+9  A: 

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";
CanSpice
Thanks. Sorry but I am getting an internal server error message when I do this.
seeker7805
Your getting a 500 Internal Server Error is a problem on your end. It does not make the answer any less correct.
Andy Lester
See [How do I troubleshoot my Perl CGI program](http://stackoverflow.com/q/2165022/8817).
brian d foy
A: 

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.
Eric Strom
A couple of edge cases to consider: (1) What happens if you've got a string of more than 45 letters without a space? (2) Given a sequence of spaces that crosses the boundary, should the spaces at position 45 and up go at the beginning of the new line, or the end of the old one, or be dropped altogether?
Jander