This nifty function will take a scalar variable containing a paragraph of text and format it to a specified width in characters. Useful for formatting reports, emails, anytime there is not an automatic wordwrap. Namaste.
#!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; }

Replies are listed 'Best First'.
Re: Force paragraph width, line length, fixed width
by MeowChow (Vicar) on Apr 27, 2001 at 00:53 UTC
    You may want to have a look at Text::Wrap or Damian Conway's Text::Autoformat.
    use Text::Wrap; $Text::Wrap::columns = 80; $text = "blah blah blah..."; print wrap('','',$paragraph);
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
      Thank you. Unfortunately all packages and modules need to go before a review process and approval here at work, so it is vanilla flavored Perl for me!

      Home made pistachio, anyone?
        Text::Wrap is in the Perl core, and as far as conducting reviews of modules written by Conway goes, one may as well conduct a source code review of Perl itself.

        Companies and their silly rules...

           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print