[comp.lang.c] Perl line-scruncher solution

merlyn@intelob.intel.com (Randal L. Schwartz @ Stonehenge) (03/31/89)

In article <623@gonzo.UUCP>, daveb@gonzo (Dave Brower) writes:
| I have two entries so far, one in "lex" and another in "awk".  Both are
| less than 20 lines.  It will be interesting to compare timings between
| awk, gawk, nawk, lex and flex.

[Okay, so I blew it on tossing comments...]

Here's my solution, just 5 lines of (mostly readable :-) Perl...

#!/usr/bin/perl
for ($file = "stdin", $line = 1; $_ = <stdin>;) {
	($line = $1, $file = $2, $sync = 0, next) if /^#\W*(\d+)\W+"(.*)"\W*$/;
	($sync = 0, $line++, next) if /^\W*$/;
	printf "#line %d \"%s\"\n", $line, $file unless $sync++;
	print; $line++;
}

Perl is so *handy* for things like this.  Please note that I only
suck from stdin... a "good" solution would probably take from '<>'
and pay attention to the changing filenames.  But, this handles
   /lib/cpp | scrunch
just fine, which I think was the original query.

Note that cpp spits out
  # 11 "foo"
even though it *wants*
  #line 11 "foo"
or
  #line "foo" 11
sigh.  (That last form will get *# "foo" 11* on the output, too... sheesh.)

With a few additional lines, I could check for #line as well.

Submitted for your approval,
-- 
/     Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095        \
|        on contract to BiiN (for now :-) Hillsboro, Oregon, USA.             |
|<@intel-iwarp.arpa:merlyn@intelob.intel.com> ...!uunet!tektronix!biin!merlyn |
\     Cute quote: "Welcome to Oregon... home of the California Raisins!"      /