«,» matches a comma, then «.+?» matches the least possible, then it matches the end of the string or a LF at the end of the string.

01234567 position A, B, C

Full:

  1. Start matching at position 0.
    1. At position 0, «,» doesn't match. ⇒ Backtrack.
  2. Start matching at position 1.
    1. At position 1, «,» matches 1 character.
      1. At position 2, «.+?» matches 1 characters.
        1. At position 3, «$» doesn't match. ⇒ Backtrack.
      2. At position 2, «.+?» matches 2 characters.
        1. At position 4, «$» doesn't match. ⇒ Backtrack.
      3. At position 2, «.+?» matches 3 characters.
        1. At position 5, «$» doesn't match. ⇒ Backtrack.
      4. At position 2, «.+?» matches 4 characters.
        1. At position 6, «$» doesn't match. ⇒ Backtrack.
      5. At position 2, «.+?» matches 5 characters.
        1. At position 7, «$» matches 0 characters. ⇒ Success.

Summary:

  1. Starts matching at position 1.
  2. At position 1, «,» matches 1 character.
  3. At position 2, «.+?» matches 5 characters.
  4. At position 7, «$» matches 0 characters.

If «.+?» were to match any less, the «$» wouldn't match.

Solution:

sub join_list { return "none" if !@_; # ??? my $last = pop; return $last if !@_; return join( ", ", @_ ) . " and " . $last; }

In reply to Re: Non-greedy substitution by ikegami
in thread Non-greedy substitution by Bod

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.