Pure Perl parser for strings related to Makefile.

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?

#!/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;
+3
source share
2

, . "perlish". :

#!/usr/bin/perl

use strict;
use warnings;

$/ = undef;             # we want no input record separator.
my $file = <>;          # slurp whole file

$file =~ s/^\n//;       # Remove newline at start of file
$file =~ s/\s+\n/\n/g;  # Remove trailing whitespace.
$file =~ s/\n\s*#[^\n]+//g;     # Remove comments.
$file =~ s/\n\s+/ /g;   # Merge continuations

# Done
print $file;
+6

, . , (), ().

#!/usr/bin/perl

use strict;
use warnings;

my @out;

while( <>)
  { chomp;
    s{#.*}{};             # suppress comments
    next unless( m{\S});  # skip blank lines
    if( s{^\s+}{ })       # does the line start with spaces?
      { $out[-1] .= $_; } # yes, continuation, add to last line
    else 
      { push @out, $_;  } # no, add as new line
  }

$, = "\n";                # set output field separator
$\ = "\n";                # set output record separator
print @out;          
+3

Source: https://habr.com/ru/post/1710630/


All Articles