ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.12. Reformatting ParagraphsProblemYour 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. SolutionUse the standard Text::Wrap module to put line breaks at the right place. use Text::Wrap; @OUTPUT = wrap($LEADTAB, $NEXTTAB, @PARA); DiscussionThe Text::Wrap module provides the 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:
We get back a single string, with newlines ending each line but the last: # merge multiple lines into one, then wrap one long line use Text::Wrap; undef $/; print wrap('', '', split(/\s*\n\s*/, <>)); If you have the Term::ReadKey module (available from CPAN) on your system, you can use it to determine your window size so you can wrap lines to fit the current screen size. If you don't have the module, sometimes the screen size can be found in The following program tries to reformat both short and long lines within a paragraph, similar to the fmt program, by setting the input record separator use Text::Wrap qw(&wrap $columns); use Term::ReadKey qw(GetTerminalSize); ($columns) = GetTerminalSize(); ($/, $\) = ('', "\n\n"); # read by paragraph, output 2 newlines while (<>) { # grab a full paragraph s/\s*\n\s*/ /g; # convert intervening newlines to spaces print wrap('', '', $_); # and format } See AlsoThe |