Reputation: 3
I have the following file :
firstname=John
name=Smith
address=Som
ewhere
As you can see, the address is on 2 lines (and the second line begins by a space).
I have to write the "good" output (with "address=Somewhere") into another file.
That's the first script (a little bit complicated) I wrote :
foreach $line (@fileIN) {
if ($lastline eq "") {
$lastline = $line;
} else {
if ($line =~/^\s/) {
print $line;
$line =~s/^\s//;
$lastline =~s/\n//;
$lastline = $lastline.$line;
} else {
print fileOUT $lastline;
$lastline = $line;
}
}
}
$line =~/^\s/ => This regex is matching spaces in the $line, but not only at the begin.
I also tried to write a simple one but it doesn't work too :
perl -pe 's/$\n^\s//' myfile
Upvotes: 0
Views: 659
Reputation: 22421
You seem to be doing too much work. I'd do it this way:
my $full_line;
foreach my $line (@fileIN) {
if ($line =~ /^\s+(.+)\Z/s){ # if it is continuation
my $continue = $1; # capture and
$full_line =~ s/[\r\n]*\Z/$continue/s; # insert it instead last linebreak
} else { # if not
if(defined $full_line){ print $full_line } # print last assembled line if any
$full_line = $line; # and start assembling new
}
}
if(defined $full_line){ print $full_line } # when done, print last assembled line if any
Upvotes: 1
Reputation: 241758
For example like this?
while (<DATA>) {
chomp;
print "\n" if /=/ and $. - 1; # do not insert empty line before the 1st line
s/^\s+//; # remove leading whitespace
print;
}
print "\n"; # newline after the last line
__DATA__
firstname=John
name=Smith
address=Som
ewhere
Upvotes: 1
Reputation: 3465
check my solution only 1 regexp :)
my $heredoc = <<END;
firstname=John
name=Smith
address=Som
ewhere
END
$heredoc =~ s/(?:\n\s(\w+))/$1/sg;
print "$heredoc";`
Upvotes: 0