#!yourshellbang $st = "Do not believe anything, no matter who says it-- not even if I say it, unless you first validate what you've understood against your own experiences. -One Buddha Or Another"; print "\n\n\@25 width: \n" . &fixparagraphwidth($st,25) . "\n\n\n"; print "\@50 width: \n" . &fixparagraphwidth($st,50) . "\n\n\n"; exit; ## accepts string and line length ## returns scalar with embedded newlines # known bug: width must be greater than shortest word # if you fix it, tell Bliss at perlmonks.org # sub fixparagraphwidth { ($paragraph, $width) = @_; $paragraph =~ s/\n/ /g; #\n into spaces $paragraph =~ s/ / /g; #remove doubled up $pos = ++$width; while () { substr($paragraph, ($pos = rindex $paragraph, ' ', $pos) , 1) = "\n"; if ( ($pos eq -1) || (($pos += $width) > length($paragraph)) ) {last;} } return $paragraph; }