How can I identify and remove redundant code in Perl?

I have a Perl code base, and there are many redundant functions, and they are distributed across many files.

Is there a convenient way to define these redundant functions in a codebase? Is there a simple tool that can check my codebase for this?

+7
perl refactoring
source share
4 answers

You can use the B :: Xref module to create cross-reference reports.

+10
source share

I have encountered this problem in the past. I hit a small little program that uses PPI to find routines. It normalizes the code a bit (space is normalized, comments are deleted) and reports any duplicates. It works well. PPI does all the hard lifting.

You can make normalization a little smarter by normalizing all variable names in each subroutine to $ a, $ b, $ c, and possibly 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; } } } 
+8
source share

It may not be convenient, but your brain is the best tool for this. Go through the entire code and familiarize yourself with its relationships. Try to see common patterns. Then refactoring!

I marked your question with refactoring . "On this site you can find interesting material on this site.

+3
source share

If you use Linux, you can use grep to help you list all the functions in your codebase. You will probably need to do what Ether offers and really go through the code to understand it if you haven't already.

Here is a simplified example:

 grep -r "sub " codebase/* > function_list 

You can also search for duplicates. This idea may be less effective if you use the features of Perl OOP.

You can also mention NaturalDocs , a tool for documenting code. This will help you move forward.

0
source share

All Articles