Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I identify and remove redundant code in Perl?

I have a Perl codebase, and there are a lot of redundant functions and they are spread across many files.

Is there a convenient way to identify those redundant functions in the codebase? Is there any simple tool that can verify my codebase for this?

like image 592
someguy Avatar asked Oct 28 '09 05:10

someguy


2 Answers

You could use the B::Xref module to generate cross-reference reports.

like image 199
David Harris Avatar answered Oct 13 '22 23:10

David Harris


I've run into this problem myself in the past. I've slapped together a quick little program that uses PPI to find subroutines. It normalizes the code a bit (whitespace normalized, comments removed) and reports any duplicates. Works reasonably well. PPI does all the heavy lifting.

You could make the normalization a little smarter by normalizing all variable names in each routine to $a, $b, $c and maybe doing something similar for strings. Depends on how aggressive you want to be.

#!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;
        }
    }
}
like image 43
Schwern Avatar answered Oct 13 '22 22:10

Schwern