perl get nested functions and parameters (text::balanced or plain perl)

Viewed 131

I have a text file with the following content and would like to extract nested functions (including rootfunc) in an array or other data structure with perl.

INPUT FILE CONTENT:

rootfunc aaa with string1 {
    blah blah
    subfunc bbb (different parameters) {
        blah blah
    }
    subfunc others_in_aaa (different parameters) {
        blah blah
    }
}

rootfunc ccc with string2 {
    blah blah
    if (blah) {
        blah blah
    } else {
        blah blah
    }
    subfunc others_in_ccc (different parameters) {
        blah blah
    }
}

rootfunc others with stringothers {
    blah blah
    subfunc others_in_others (different parameters) {
        blah blah
    }
}

I would like to extract all the rootfunc and subfunc with the output like below:

INTENDED OUTPUT FILE (not, the if/else are also stripped out):

rootfunc aaa with string1 {
    subfunc bbb (different parameters) {
    }
    subfunc others_in_aaa (different parameters) {
    }
}

rootfunc ccc with string2 {
    subfunc others_in_ccc (different parameters) {
    }
}

rootfunc others with stringothers {
    subfunc others_in_others (different parameters) {
    }
}

With the perl script as follow I can only extract whatever is in the bracket of rootfunc and then get whatever is in subfunc, but the rootfunc name/parameters and subfunc name/parameters are lost:

PERL SCRIPT:

use Text::Balanced qw(extract_multiple extract_bracketed);

open(FILE, "/tmp/a") || die "Unable to open /tmp/a: $!\n";
{
    local $/=undef;
    my $file = <FILE>;
}
close(FILE);
my @array = extract_multiple($file, [sub{extract_bracketed($_[0], '{}')},], undef, 1);

Is there any method to get the desired output? Thanks,

1 Answers
Related