解析文本文件并在perl中提取信息

时间:2015-04-02 06:21:04

标签: perl parsing text

我有一个包含多个功能的代码

void fun_one()

{

tempa=10;

tempb=10;

}

void fun_two()

{

tempc=12;

tempd=13;

}

如果我输入变量名,我想要提取函数名的perl代码;

说我搜索" tempa",它应该提取" fun_one"变成一个变量;

说我搜索" tempd"它应该提取" fun_two"变成一个变量;

我提取了行号

open my $code, '<', 'code.txt'  ;

my $keyword = "tempa";

my $regex = qr|\b($keyword)\b|;


while ($code>)

{

    while (/$regex/g)

    {

        print "$.\n";

    }

}

输出:3 我需要一些逻辑来提取功能名称。

提前致谢

1 个答案:

答案 0 :(得分:0)

您可能需要解析器而不仅仅是正则表达式。

但是...

sub find_function_using_variable {
  my $variable = shift;
  my $last_func="";
  while (<>) {
    $last_func = $1 if m/void (\w+)\(\)/;
    print $last_func."\n" if m/\Q$variable\E/;
  }
}
相关问题