while ( reading from the input file yields a line of data ) { if ( the line begins with "RS," ) { replace the newline character(s) at the end of the line with a comma save this line in a variable called $line_out } elsif ( the line begins with "RAd," ) { replace the final newline character(s) with a comma (just like above) append this line to $line_out } elsif ( the line begins with "RC," ) { print $line_out with the current line appended to it. } } #### use strict; use warnings; my $line_out; open ( MOV, "<", "test.cxv" ) or die "test.csv: $!\n"; while () { if ( /^RS,/ ) { s/\s+$/,/; $line_out = $_; } elsif ( /^RAd,/ ) { s/\s+$/,/; $line_out .= $_; } elsif ( /^RC,/ ) { print $line_out . $_; } }