views:

73

answers:

3

In Perl, working with a paragraph of text in one big long string with no line breaks, how can I use a split and RegEx (or something else) to split the paragraph into chunks of around the same size at a word boundary, for display in a monospaced font?

For example, how do I change this:

"When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community."

into this:

"When you have decided which answer is the most \n"
"helpful to you, mark it as the accepted answer \n"
"by clicking on the check box outline to the \n"
"left of the answer. This lets other people \n"
"know that you have received a good answer to \n"
"your question. Doing this is helpful because \n"
"it shows other people that you're getting \n"
"value from the community.\n"

Thanks, Ben

+4  A: 

Check out Text::Wrap.

Ether
+4  A: 

Of course, use Text::Wrap. But, here is an illustration just for the heck of it:

#!/usr/bin/perl

use strict; use warnings;

use constant RIGHT_MARGIN => 52;

my $para = "When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community.";

my ($wrapped, $line) = (q{}) x 2;

while ( $para =~ /(\S+)/g ) {
    my ($chunk) = $1;
    if ( ( length($line) + length($chunk) ) >= RIGHT_MARGIN ) {
        $wrapped .= $line . "\n";
        $line = $chunk . ' ';
        next;
    }
    $line .= $chunk . ' ';
}

$wrapped .= $line . "\n";

print $wrapped;
Sinan Ünür
+3  A: 

Just since its not here, this isn't all that hard with a regex:

$str =~ s/( .{0,46} (?: \s | $ ) )/$1\n/gx;

The substitution inserts a newline after up to 46 characters (matches the OP example) followed by a space or the end of the string. The gmodifier repeats the operation across the entire string.

Eric Strom