perl - 需要将提取的函数参数添加到模板中

时间:2013-10-15 13:03:12

标签: regex perl

这是关于以下问题的背景

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

但是我不需要在函数顶部添加注释,而是需要在模板中添加它。

喜欢@param [in] pChainCtrl

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

我的代码来自用户@Joseph的输入,它在函数定义之上添加参数但不在模板中添加

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)
}

1 个答案:

答案 0 :(得分:1)

此代码似乎提供了您想要的输出:(根据评论编辑)

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,
)
{
    {....}
}
.........

输出:

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