in reply to Include Delimiter in Split Output

If you'd like the output of a split to keep the delimiter in the output string, you can use look ahead or look behind assertions (Looking ahead and looking behind), depending on which side you want the delimiter to stick to. For example:

#!/usr/bin/perl use strict; use warnings; while (<DATA>) { my @line = split/(?<=x)/; print join "\n", @line; } __DATA__ 1234x456x789

However, this means that one of the records will be inconsistently formatted as compared to the others, which is generally something to be avoided. It usually makes a lot more sense to just append the new lines after the split (perhaps using .=) or include the formatting in your print statement.

Replies are listed 'Best First'.
Re^2: Include Delimiter in Split Output
by ssandv (Hermit) on Jul 30, 2009 at 16:25 UTC
    Indeed. If the goal, as stated in the OP, is "output to include the blank line", then you probably shouldn't put it in the element, you should put it in your output--print/say/whatever--because otherwise your last element will look different than the rest when you print them out (and any regex mucking about you do on them may behave differently on the last element).