n.b. Please drop the "\r". You should never hardcode a CR into plain text, in Perl. Let the automatic conversion from "\n" to CRLF, when printing to a filehandle without binmode applied, on a platform that wants the CRs, take care of that. "\n" is the logical end-of-line character, on any platform.

But, that aside, even though you're well on the way, your program has a bug. It will try to add a linebreak in the last line, even if it's narrow enough to fit onto one line. Why would it do that? Because

$_ = "Hello, world!"; /.{0,76}\s/;
matches the space between "Hello," and "world!".

I'd change the regexp to the following:

s/[^\n\S]*(.{1,76})(?:\s|$)/$1\n/g;
with the following rationale: But, I admit: mine doesn't quite look as easy as yours, any more. :)

In reply to Re: Easy Solution by bart
in thread Matching positions with lookarounds by blahblah

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.