如何在Perl中识别和删除冗余代码?

som*_*guy 7 perl refactoring

我有一个Perl代码库,并且有很多冗余功能,它们分布在许多文件中.

有没有方便的方法来识别代码库中的冗余功能?有没有可以验证我的代码库的简单工具?

Dav*_*ris 10

您可以使用B :: Xref模块生成交叉引用报告.


Sch*_*ern 8

我过去曾经遇到过这个问题.我打了一个快速的小程序,使用PPI查找子程序.它对代码进行了规范化(空格规范化,删除了注释)并报告任何重复.工作得相当好.PPI完成了所有繁重的工作.

你可以通过将每个例程中的所有变量名称规范化为$ a,$ b,$ c来使规范化变得更加智能,并且可以对字符串做类似的事情.取决于你想要多么具有侵略性.

#!perl

use strict;
use warnings;

use PPI;

my %Seen;

for my $file (@ARGV) {
    my $doc = PPI::Document->new($file);
    $doc->prune("PPI::Token::Comment");         # strip comments

    my $subs = $doc->find('PPI::Statement::Sub');
    for my $sub (@$subs) {
        my $code = $sub->block;
        $code =~ s/\s+/ /;                      # normalize whitespace
        next if $code =~ /^{\s*}$/;             # ignore empty routines

        if( $Seen{$code} ) {
            printf "%s in $file is a duplicate of $Seen{$code}\n", $sub->name;
        }
        else {
            $Seen{$code} = sprintf "%s in $file", $sub->name;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)