Reformatting Paragraphs
Problem
Your string is too big to fit the screen, and you want to break it up into lines of words, without splitting a word between lines. For instance, a style correction script might read a text file a paragraph at a time, replacing bad phrases with good ones. Replacing a phrase like utilizes the inherent functionality of with uses will change the length of lines, so it must somehow reformat the paragraphs when they’re output.
Solution
Use the standard Text::Wrap module to put line breaks at the right place.
use Text::Wrap; @OUTPUT = wrap($LEADTAB, $NEXTTAB, @PARA);
Discussion
The Text::Wrap module provides the wrap function,
shown in Example 1.3, which takes a list of lines
and reformats them into a paragraph having no line more
than
$Text::Wrap::columns characters long. We set
$columns to 20, ensuring that no line will be
longer than 20 characters. We pass wrap two
arguments before the list of lines: the first is the indent for the
first line of output, the second the indent for every subsequent
line.
Example 1-3. wrapdemo
#!/usr/bin/perl -w
# wrapdemo - show how Text::Wrap works
@input = ("Folding and splicing is the work of an editor,",
"not a mere collection of silicon",
"and",
"mobile electrons!");
use Text::Wrap qw($columns &wrap);
$columns = 20;
print "0123456789" x 2, "\n";
print wrap(" ", " ", @input), "\n";The result of this program is:
01234567890123456789
Folding and
splicing is the
work of an
editor, not a
mere collection
of silicon and ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access