Ad-vic
Ad-vic

Reputation: 529

perl - need to add function arguments extracted into template

This is in context to following question

perl - extracting arguments from function definitions and putting it as comment above it

But instead of adding comment just in top of function, I need to add it inside template.

like @param[in ] pChainCtrl

/**
********************************************************************************
*  @fn ChainCtrlInitChains                                                     
*  @brief
*  @param[in ]     # need to add arguments here
*  @return
********************************************************************************
*/
eErrorT ChainCtrlInitChains(ChainCtrlT* pChainCtrl,
   char* name,
   int instance,
   void* pOwner,
   )
   {
       ....
   }
   .........

My code with input from user @Joseph which adds arguments above function definitions but not inside the template

use File::Copy;

open my $FILE,'<','a.c' or die "open failed: $!\n";
open my $FILE1,'>','b.c' or die "open failed: $!\n";

$file_slurp = do { local $/;<$FILE>};
$file_slurp =~ s{ ^ ( \w+ \s+ \w+ \s* \( (.+?) \) )}{&print_args($2,$1)}xmesg;
print $FILE1 $file_slurp;

close($FILE);
close($FILE1);

sub print_args {
    ($args,$proto) = @_;
    @arr = map /(\w+)$/, split /\W*?,\W*/, $args;
    @comments = map ' *  @param[in/out] '."$_", @arr;
    return join "\n",(@comments,$proto)
}

Upvotes: 0

Views: 92

Answers (1)

jing yu
jing yu

Reputation: 264

This code seems to give your desired output:(edited as per comment)

my $file_slurp = do { local $/;<DATA>};

#Note this '({(?:[^{}]++|(?3))*+})' extra bit in the pattern match is to match paired '{}'
while ($file_slurp =~ /^ \S+ \s+ (\S+) \s* (\( .+? \))\s+ ({(?:[^{}]++|(?3))*+}) /xsmgp) {
    my $func = $1;
    my $match = ${^MATCH};
    my @args = $2 =~ /(\w+)[,)]/g; 
    print_args($func,$match,@args);
}

sub print_args {
    my $func = shift;
    my $match = shift;
    my @args = @_;
    my @fields = qw/@fn @brief @param[in] @return/;
    $fields[0].=' '.$func;
    $fields[2].=' '.join ' ', @args;
    say '/**';
    say '*' x 20;
    say '*  '.$_ for @fields;
    say '*' x 20;
    say '*/';
    say $match;
}

__DATA__
eErrorT ChainCtrlInitChains(ChainCtrlT* pChainCtrl,
char* name,
int instance,
void* pOwner,
)
{
    {....}
}
.........

Output:

/**
********************
*  @fn ChainCtrlInitChains
*  @brief
*  @param[in] pChainCtrl name instance pOwner
*  @return
********************
*/
eErrorT ChainCtrlInitChains(ChainCtrlT* pChainCtrl,
char* name,
int instance,
void* pOwner,
)
{
    {....}
}

Upvotes: 1

Related Questions