If you wrap in parens your split RE, you capture (as though it were one of the split results) whatever matched the split regexp.

If you split using a lookahead assertion, nothing is gobbled up.

These are two different approaches that yield different results, but both deserve mentioning. I will demonstrate both, but first, the normal, common, run-of-the-mill split:

my $string = "This and that"; print "$_\n" for split /\s+and\s+/, $string; __OUTPUT__ This that

That was the simple, and standard case. Now for the capturing method:

my $string = "This and that"; print "$_\n" for split /\s+(and)\s+/, $string; __OUTPUT__ This and that

And now for the lookahead assertion method:

my $string = "This and that"; print "$_\n" for split /(?=\s+and\s+)/, $string; __OUTPUT__ This and that

That third example is the trickiest. It basically matches (and thus splits) at the point at which the lookahead assertion begins, and because lookahead assertions are only assertions, they don't gobble anything at all, and thus, everything after the split-point is preserved as-is. Use care with this method; lookahead assertions are difficult to do right in split functions. Read the docs on split for details.

Just for completeness, I want to demonstrate the lookahead assertion version with a split that has more than two resulting substrings as its outcome:

my $string = "This and that and those too"; print "$_\n" for split /(?=\s+and\s+)/, $string; __OUTPUT__ This and that and those too

...that's pretty much what you were looking for, right? That's a great question, by the way.


Dave


In reply to Re: split but not consumed by davido
in thread split but not consumed by jcpunk

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.