$test =~ s/,(.+?)$/ and$1/; ALWAYS goes to the first comma and the rest is anchored to the end of the line so it will always match everything to the end of the line. Without the anchor it would match the next character after the comma (the space character.)

There are a few different ways to match the last comma:

$ perl -le'my @x = ( "A", "A, B", "A, B, C" ); # 1a for my $test ( @x ) { $test =~ s/(.*),/$1 and/s; print $test; } ' A A and B A, B and C $ perl -le'my @x = ( "A", "A, B", "A, B, C" ); # 1b for my $test ( @x ) { $test =~ s/.*\K,/ and/s; print $test; } ' A A and B A, B and C $ perl -le'my @x = ( "A", "A, B", "A, B, C" ); # 2a for my $test ( @x ) { $test =~ s/,([^,]*)\z/ and$1/; print $test; } ' A A and B A, B and C $ perl -le'my @x = ( "A", "A, B", "A, B, C" ); # 2b for my $test ( @x ) { $test =~ s/,(?=[^,]*\z)/ and/; print $test; } ' A A and B A, B and C $ perl -le'my @x = ( "A", "A, B", "A, B, C" ); # 3 for my $test ( @x ) { $test = reverse $test; $test =~ s/,/dna /; $test = reverse $test; print $test; } ' A A and B A, B and C

Which one you use will depend on how much data you have to process.

Naked blocks are fun! -- Randal L. Schwartz, Perl hacker

In reply to Re: Non-greedy substitution by jwkrahn
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.