Contributed by Anonymous Monk
on Apr 21, 2000 at 19:18 UTC
Q&A
> strings
Description: I've got a string of undertermined length,
which will contain text with embedded newlines.
I'd like to split this string into chunks of no
more than 140 characters (but splitting on a word
boundry, so as to not cut words apart).
Ideally, I'd like to be left with an array
containing the split strings. Answer: How can I split a line close to a certain length, but on a word boundary? contributed by poznick and true to the perl motto, here's yet another (much simpler) way to do it:
@text = $messagebody =~ /(.{1,140}\W)/gms;
| Answer: How can I split a line
close to a certain length, but on a word boundary? contributed by chromatic The Text::Wrap module might prove useful to you. Your code might look like this:
use Text::Wrap qw(wrap 140 'wrap');
@strings = split/\n\n/, wrap($text);
| Answer: How can I split a line close to a certain length, but on a word boundary? contributed by poznick I ended up using:
$rest = $messagebody;
@text=();
while($rest ne '') {
$rest =~ /(.{1,140}\W)/ms;
push @text, $1;
$rest = $';
}
Text::Wrap doesn't provide the desired behavior,
unless I were to do a tr/// to translate all the
newlines into some strange character, do the wrap,
and then tr the strange characters back to newlines.
This way seemed a little cleaner. |
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.
|
|