tags:

views:

74

answers:

1

Hi,

I'm looking to extract a statement of C code given the filename and linenumber where it begins.

I can't, of course, just take the line, as I could have something like:

foo(i,
   j, "this is ); \
   ", k);

as the example indicates, I also can't look for the next ); either, which would make it fairly simple.

Is there anything out there, presumably on CPAN, which does this automatically?

If I could run the code through indent first, I would have it allow unlimited line lengths, and then take just that line, but if I do that, I lose the line number!

+5  A: 

To do this perfectly well, you'd need a full-blown C parser in Perl. However, you can cover probably more than 99% of all cases with a much simpler algorithm:

  1. Open the file
  2. Skip lines until you reach the line in question
  3. Slurp lines until you reach a semicolon at the end of the line

"Semicolon at end of line" is a pretty decent heuristic for "end of statement". Relatively simple quote-parsing might protect you from the situation shown above.

If you need something more sophisticated than that, you might look at C::Scan and its subclasses, or Inline::C::ParseRecDescent.

JSBangs
C::Scan looks very interesting. thanks
Mikeage