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


in reply to Word wrapping using a regex.

Your regex is obviously not working properly, because it prints beyond the boundary of 50 characters. Here's another option:

use strict; use warnings; my $string = "I'm trying to have a word wrapping using a regex in Perl +. What I would like is about every 50 characters or so to check for +the next white-space occurrence and replace that space with a newline +, and then do this for the whole string. I'd like to avoid looping o +ne character at a time or using substr or placing the value into an a +rray if possible. The code sample I have works, I'd like someone opti +on and suggestion is there a better way or better regular expression +to accomplish this."; print '1234567890'x5 . "\n"; print wrap($string, 50) . "\n"; sub wrap { my ($s, $wrap) = @_; my (@lines, $line); while (length $s > $wrap) { ### Take one extra character so we can see if ### we're wrapping inside a word or not $line = substr($s, 0, $wrap+1); $line =~ s/\s+(\S*)$//; push @lines, $line; ### Add any word fragments back on $s = $1 . substr($s, $wrap); $s =~ s/^\s+//; } return join "\n", @lines; }

Replies are listed 'Best First'.
Re^2: Word wrapping using a regex.
by Additude (Initiate) on Nov 14, 2012 at 14:26 UTC
    I think to make this work we need to add another line at the end to tell it what to do with the last of the string that is less than $wrap.
    sub wrap { my ($s, $wrap) = @_; my (@lines, $line); while (length $s > $wrap) { ### Take one extra character so we can see if ### we're wrapping inside a word or not $line = substr($s, 0, $wrap+1); $line =~ s/\s+(\S*)$//; push @lines, $line; ### Add any word fragments back on $s = $1 . substr($s, $wrap); $s =~ s/^\s+//; } push @lines, $s; ## Adds the the last of the $s string to @lines return join "\n", @lines; }