in reply to split but not consumed
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
|
|---|