Contributed by anthonysj
on Oct 18, 2000 at 19:23 UTC
Q&A
> data formatting
Description:
I'm reading text from a file where each paragraph is stored as a single line.
Some of the these lines are quite long.
How can I print the text so that it wraps each paragraph to lines that are no more than 70 characters long?
Answer: How to wrap text to a maximum width of 70 characters per line? contributed by cwest
Text::Wrap does this.
use Text::Wrap;
$Text::Wrap::columns = 70;
print Text::Wrap::fill( '', '', join '', <DATA> );
__DATA__
This is a huge paragraph that no doubt spans quite a number of columns
+. My guess is that it may even span past 70 Columns, so we'll use the
+ nifty Text::Wrap module to limit the number of columns that this par
+agraph can take up to 70.
| Answer: How to wrap text to a maximum width of 70 characters per line? contributed by japhy
You can use formats:
format =
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
$string
.
$string = get_some_really_long_string();
write;
See perldoc perlform.
| Answer: How to wrap text to a maximum width of 70 characters per line? contributed by cLive ;-)
(Assuming you don't want paragraphs to wrap in the middle of words.)
Here's a nice little regex solution:
$paragraph =~ s/([^\n]{0,70})(?:\b\s*|\n)/$1\n/gi;
Or genericized to any width, determined by a variable:
my $max_width = 40;
$paragraph =~ s/([^\n]{0,$max_width})(?:\b\s*|\n)/$1\n/gio;
Smart Substrings has some interesting insight. Combining that with the solution above:
$paragraph =~ s/([^\n]{50,70})(?:\b\s*|\n)/$1\n/gi;
while ( $paragraph =~ m/([^\n]{71})/ )
{
$paragraph =~ s/([^\n]{70})([^\n])/$1\n$2/g;
}
In other words, split lines which are more than 70 chars long and include no spaces.
(Not sure the loop is necessary...)
|
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|