If you have a line of text you wish to break into two lines of nearly the same length, this regex is for you.
$str = "of course, japhy thought of this one"; $half = int(length($str)/2); $str =~ s {( ?)([^ ]*)(?<=^.{$half})([^ ]*)( ?)} { length($2) < length($3) ? "\n$2$3$4" : "$1$2$3\n" }e; print $str; __END__ of course, japhy thought of this one
This determines the midpoint of your string, and then looks for a space (if there is one) followed by non-spaces, stopping at the middle of the string, and then looks for non-spaces followed by a space (if there is one). Then, based on the lengths of the non-space sections, it determines where to insert the newline. Centering this content, if wanted, is then child's play.

In reply to Similar-length lines by japhy

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.