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;
}
|