O wise monks, this is probably one of those questions that has a simple, obvious answer that I'm just not seeing because I've been looking at it too long.

I have the following input:

mono-basic-2.10
mono-2.10.2-r1
mono-2.10.5
I need to split each line into a package name and a version string. Because the hyphen may occur in either part, I need a regex that is smart enough to figure out which hyphen to split on.

This regex seems to work:

foreach $line (<STDIN>) { chomp $line; $line =~ s/-(?=[^-]+(-r[0-9]+)?$)/ ==> /; print "$line\n"; }
in that it turns the correct hyphen into a more obvious separator, outputting:
mono-basic   ==>   2.10
mono   ==>   2.10.2-r1
mono   ==>   2.10.5
However, if I use the exact same regex in the split function:
foreach $line (<STDIN>) { chomp $line; ($package, $ver) = split /-(?=[^-]+(-r[0-9]+)?$)/, $line; print "$package ==> $ver\n"; }
it doesn't work:
mono-basic   ==>   
mono   ==>   -r1
mono   ==>   
Giving split a LIMIT of 2 doesn't change the output; the actual version numbers are eaten, and only the trailing -r1 on the second line makes it into $ver. What is it about split's processing of the regex that is different from that of the substitute operator?

$ perl --version

This is perl 5, version 12, subversion 3 (v5.12.3) built for i686-linux
(with 13 registered patches, see perl -V for more detail)

In reply to regex behaves differently in split vs substitute? by raygun

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.