Piodo Piodo - 7 months ago 13
Perl Question

Perl regex - Find functions in C file and print their definitions

-- UPDATED --

I want to find C functions in file and print their definitios

For example:

For this input:

#include <stdlib>

int function(int a)
{
return a;
}

void func2()
{
int b = 1;
}

int func3(int a,int b)
{
a = a +b;
while(x) {
x--;
}
return a;
}

int main(int argc, char* argv[])
{
int x=(a+1);
return 0;
}


The output should be:

int function(int a);
void func2();
int func3(int a,int b);


This is my code:

#!/usr/bin/perl -w
open(FILE, "<", $ARGV[0]) or die "file open error";

if ( @ARGV ) #if there are args
{
if ( -f $ARGV[0] ) #if its regular file
{

while(<FILE>)
{
if ($_ =~ /(.+)\s(.+)\(/){
print $1; # type in arg $1
print "\n";
print $2; # name in arg $2
print "\n";
}
}
}
else{
print "Arg is not a file\n";}
}
else{
print "no args\n";}


I end with function type in arg $1 and function name in $2. I want to get the full name and args in '()' brackets in $2. How to avoid 'main' word? the '^[(main)] doesnt work. In the end I want to print it all with ';' at the end.

It needs to check for {} brackets to not print for example: int x=(a+1);

Answer

Try /(\S+)\s+(\S+\([^)]*\))/ and then print $1+$2+";\n".

To prevent main with negative lookahead:

/(\S+)\s+((?!main)\S+\([^)]*\))/

If lookahead is not supported:

/(\S+)\s+((m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)\([^)]*\))/

The part responsible for avoiding main:

(m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)