http://www.perlmonks.org?node_id=8383

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

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.

Replies are listed 'Best First'.
Re: How can I split a line close to a certain length, but on a word boundary?
by poznick (Initiate) on Apr 25, 2000 at 02:07 UTC
    and true to the perl motto, here's yet another (much simpler) way to do it:
    @text = $messagebody =~ /(.{1,140}\W)/gms;
    
Re: How can I split a line close to a certain length, but on a word boundary?
by chromatic (Archbishop) on Apr 21, 2000 at 20:12 UTC
    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);
Re: How can I split a line close to a certain length, but on a word boundary?
by poznick (Initiate) on Apr 24, 2000 at 21:41 UTC
    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.