Yup, no matter what you’re doing, “look around ... CPAN has already done it!”
Having said that, the algorithm that first occurred to me consists of splitting the string into an array, then building up the output string one word at a time, spitting out each partial string as you go. (This example has many warts in it.)
use strict; use warnings;
my $str =
"This is a very long string more than thirty characters wide.";
my @split = split(/\s+/, $str);
my $output = '';
foreach my $word (@split) {
$output .= "$word ";
if (length($output) > 30) {
print "$output\n";
$output = '';
}
}
print "$output\n";
This is a very long string more
than thirty characters wide.