$text =~ s/(.{30,40}(?<=\s\b))/$1\n/mg; #### use Text::Autoformat qw(autoformat); $newtext = autoformat($text, { left=>1, right=>40, all=>1 });