How can I word wrap a string in Perl?

Look at modules like Text::Wrap or Text::Autoformat.

Depending on your needs, even the GNU core utility fold(1) may be an option.


s/(.{70}[^\s]*)\s+/$1\n/

Consume the first 70 characters, then stop at the next whitespace, capturing everything in the process. Then, emit the captured string, omitting the whitespace at the end, adding a newline.

This doesn't guarantee your lines will cut off strictly at 80 characters or something. There's no guarantee the last word it consumes won't be a billion characters long.


You can get much, much more control and reliability by using Text::Format

use Text::Format;
print Text::Format->new({columns => 70})->format($text);

Welbog's answer wraps at the first space after 70 characters. This has the flaw that long words beginning close to the end of the line make an overlong line. I would suggest instead wrapping at the last space within the first, say, 81 characters, or wrapping at the first space if you have a >80 character "word", so that only truly unbreakable lines are overlong:

s/(.{1,79}\S|\S+)\s+/$1\n/g;

In modern perl:

s/(?:.{1,79}\S|\S+)\K\s+/\n/g;

Tags:

String

Regex

Perl