我正在编写的 perl 脚本需要解析具有像 Makefile 这样的连续行的文件。即以空格开头的行是前一行的一部分。
我写了下面的代码,但不觉得它很干净或 perl-ish(见鬼,它甚至不使用“重做”!)
有许多边缘情况:奇数位置的 EOF、单行文件、以空行(或非空行或续行)开头或结尾的文件、空文件。我所有的测试用例(和代码)都在这里:http ://whatexit.org/tal/flatten.tar
你能写出通过我所有测试的更干净,perl-ish 的代码吗?
#!/usr/bin/perl -w
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*#/; # skip comments
$nextline =~ s/\s+$//g; # remove trailing whitespace
if (eof()) { # Handle EOF
$nextline =~ s/^\s+/ /;
if ($nextline =~ /^\s+/) { # indented line
&$processref($line . $nextline);
}
else {
&$processref($line);
&$processref($nextline) if $nextline ne '';
}
$line = '';
}
elsif ($nextline eq '') { # blank line
&$processref($line);
$line = '';
}
elsif ($nextline =~ /^\s+/) { # indented line
$nextline =~ s/^\s+/ /;
$line .= $nextline;
}
else { # non-indented line
&$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;