A perl script I am writing, I need to parse a file that has continuation lines like Makefile. that is, lines starting with spaces are part of the previous line.
I wrote the code below, but I donβt feel that it is very clean or perl-ish (hell, it doesnβt even use "repeat"!)
There are many edge cases: EOF in odd places, single-line files, files that start or end with an empty line (or non-empty line or continuation), empty files. All my test cases (and code) are here: http://whatexit.org/tal/flatten.tar
Can you write cleaner, perl-ish, code that passes all my tests?
use strict;
sub process_file_with_continuations {
my $processref = shift @_;
my $nextline;
my $line = <ARGV>;
$line = '' unless defined $line;
chomp $line;
while (defined($nextline = <ARGV>)) {
chomp $nextline;
next if $nextline =~ /^\s*#/;
$nextline =~ s/\s+$//g;
if (eof()) {
$nextline =~ s/^\s+/ /;
if ($nextline =~ /^\s+/) {
&$processref($line . $nextline);
}
else {
&$processref($line);
&$processref($nextline) if $nextline ne '';
}
$line = '';
}
elsif ($nextline eq '') {
&$processref($line);
$line = '';
}
elsif ($nextline =~ /^\s+/) {
$nextline =~ s/^\s+/ /;
$line .= $nextline;
}
else {
&$processref($line) unless $line eq '';
$line = $nextline;
}
}
&$processref($line) unless $line eq '';
}
sub process_one_line {
my $line = shift @_;
print "$line\n";
}
process_file_with_continuations \&process_one_line;
source
share