in reply to Split on Blank Line into array, and keep the blank line in the array

It is difficult to know what you intend from your code without sight of the data but as a general answer, if you use parentheses in the split regular expression to capture what you split on, it will be preserved in the resultant list or array.

$ perl -le ' > $str = q{abcDEfghIjkLmn}; > @arr = split m{([A-Z]+)}, $str; > print for @arr;' abc DE fgh I jk L mn $

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Split on Blank Line into array, and keep the blank line in the array
by RBBD (Initiate) on May 23, 2009 at 00:09 UTC
    The source file has a \n at the end of the last line of each section, plus another \n to create the blank line. I wish the content of the array to be identical. I have read much about parentheses to preserve the delimiter, but have not been able to get that to work with the blank line delimiter. All help much appreciated...

      This may do what you want. It uses a positive look-behind assertion so that the pattern splits on multiple newlines as long as thet are preceded by a newline. There ia also a look behind to cope with bank lines at the start of your data in case you need that. If you do, there will be an empty record at the start of your array that you can shift away.

      use strict; use warnings; my $startOffset = tell DATA; my $recordCt; my @records = do { local $/; split m{(?x) (?: (?<=\A) | (?<=\n) ) (\n+) }, <DATA>; }; $recordCt = 0; print qq{@{ [ sprintf qq{\n%2d >}, ++ $recordCt ] }$_<} for @records; __END__ Record 1 consists of three lines of data terminated by a newline Record 2 has just two lines terminated by a newline Record 3 contains four lines of data which is very important to the project, newline terminated again Record 4 was preceded by two blank lines and has two lines terminated by a newline

      The output.

      1 >Record 1 consists of three lines of data terminated by a newline < 2 > < 3 >Record 2 has just two lines terminated by a newline < 4 > < 5 >Record 3 contains four lines of data which is very important to the project, newline terminated again < 6 > < 7 >Record 4 was preceded by two blank lines and has two lines terminated by a newline <

      Note that records 2, 4 and 6 are the newlines we preserved with the regex captures and each record finishes with a newline as you can see from the positions of the '<'s.

      I hope this is helpful.

      Cheers,

      JohnGG