简体   繁体   English

根据文件名+行号使用perl提取一行C代码

[英]Extract a line of C code using perl based on filename + line number

I'm looking to extract a statement of C code given the filename and linenumber where it begins. 我希望提取给定文件名和行号的C代码语句。

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? 大概在CPAN上有什么自动执行的吗?

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! 如果我可以先通过缩进来运行代码,我将允许它允许无限制的行长,然后只接受该行,但是如果这样做,我将丢失行号!

To do this perfectly well, you'd need a full-blown C parser in Perl. 为了完美地做到这一点,您需要在Perl中使用成熟的C解析器。 However, you can cover probably more than 99% of all cases with a much simpler algorithm: 但是,使用更简单的算法,您可以覆盖所有案例的99%以上:

  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 . 如果您需要比这更复杂的内容,可以查看C :: Scan及其子类或Inline :: C :: ParseRecDescent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM