John Doe John Doe - 6 months ago 20
Perl Question

how do I join multiple lines into one element of an array in PERL?

#L_ENTRY <s_slash_1>
#LEX </>
#ROOT </>
#POS <sp>
#SUBCAT <slash>
#S_LINK <>
#BITS <>
#WEIGHT <0.1>
#SYNONYM <0>

#L_ENTRY <s_comma_1>
#LEX <,>
#ROOT <,>
#POS <sp>
#SUBCAT <comma>
#S_LINK <>
#BITS <>
#WEIGHT <0.1>
#SYNONYM <0>

#L_ENTRY <s_tilde_1>
#LEX <~>
#ROOT <~>
#POS <sp>
#SUBCAT <tilde>
#S_LINK <>
#BITS <>
#WEIGHT <0.1>
#SYNONYM <0>

#L_ENTRY <s_at_1>
#LEX <@>
#ROOT <@>
#POS <sp>
#SUBCAT <at>
#S_LINK <>
#BITS <>
#WEIGHT <0.1>
#SYNONYM <0>


Above is my text file. I want to join each line into one element of an array until there is a 'return' and continue to join the next lines until there is another 'return'. In the text above, there are three returns, so what I want is an array of four elements.

Thank you in advance!

Answer

Please try this:

use strict;
use warnings;

my $lines = "";
my @line;
my $el = '1';
while(<DATA>)
{
    if($_!~m/^$/i) {  $lines .= "$_\n"; }
    elsif($_=~m/^$/i) {
        $lines=~s/\n{1,}/\n/g;
    push(@line, "\n\n<array-$el>$lines</array-$el>"); $el++;  $lines = ""; }
}

print @line;
Comments