Skip to content

Instantly share code, notes, and snippets.

@Chubek
Last active March 1, 2024 22:25
Show Gist options
  • Save Chubek/c1e7520d1f13c4a7b487578d4e3d5acf to your computer and use it in GitHub Desktop.
Save Chubek/c1e7520d1f13c4a7b487578d4e3d5acf to your computer and use it in GitHub Desktop.
Simple Preprocessor in Perl for any File!

preprocess.pl is a 'general-purpose preprocessor' -- a very simple one at that. All it can do is to include files, and define simple phrases.

It currently accepts input via STDIN, and outputs the preprocessed file via STDOUT. There are two directives:

#include <path_to_file.ext>

#define Id Def

I am using it to preprocess OCaml. You can use it to preprocess anything.

#!/usr/bin/perl
use strict;
use warnings;
my @includes;
my @def_names;
my %def_values;
my @regulars;
my $posix_filepath_regex = qr{/?(?:[\w.-]+/)*[\w.-]+\b};
while (<STDIN>) {
if (/^#include\s+<($posix_filepath_regex)>\s*$/) {
push @includes, $1;
} elsif (/^#define\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+(.+)\s*$/) {
push @def_names, $1;
$def_values{$1} = $2;
} else {
push @regulars, $_;
}
}
foreach my $arg (@ARGV) {
if (index($arg, "-D") == 0) {
$arg = substr($arg, 2);
my ($name, $def) = split /=/, $arg;
$def_values{$name} = $def;
} elsif (index($arg, "-I")) {
$arg = substr($arg, 2);
push @includes, $arg;
}
}
foreach my $filepath (@includes) {
open (my $inc, "<", $filepath) || die "File not found";
while (<$inc>) {
print $_;
}
}
foreach my $line (@regulars) {
foreach my $name (@def_names) {
my $value = $def_values{$name};
$line =~ s/\b$name\b/$value/g;
}
print $line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment