9.2 Eliminating Superfluous Code

Previous Table of Contents Next

9.2 Eliminating Superfluous Code

When you're faced with a mountain of code dripping all over your editor, you might want all the help you can get telling whether it's all used. It's not uncommon for people to write code that might have been used to begin with, but eventually became superfluous. So here are some ways of spotting unused code en masse.

9.2.1 Devel::Coverage

Randy J. Ray's Devel::Coverage is a module for code coverage analysis; reporting the lines of code that are visited during execution of a program. The module hasn't been changed in a while, but it still works with the current development version of Perl 5.9.0 as of the time of writing.

Devel::Coverage is a debugger plug-in, which means that it is invoked by enabling Perl's run time debugger hooks, which fire on each statement about to be executed, among other things. The interactive command-line debugger that comes with perl is itself a debugger plug-in. Devel::Coverage, however, generates a data file in response to those hook calls. That data file is not intended to be human-readable; you should run it through the program coverperl that comes with Devel::Coverage.

You use Devel::Coverage by invoking it on the command line as an argument to the -d flag:

% perl -d:Coverage program arguments...

The program will run, and the coverage file program.cvp will be created. The following is a fragment of output from coverperl for a module called Solution.pm:

12  Solution::print

        12   line 37

        12   line 38

        96   line 39

        768  line 40

        96   line 42

        12   line 44

0   Solution::setSize

        0    line 107

        0    line 108

        0    line 109

        0    line 112

7522 Solution::string

        7522 line 94

        75220 line 95

3761 Solution::transform

        3761 line 99

        3761 line 100

        37610 line 101

        3761 line 102

        3761 line 103

There is a line printed for every subroutine and every executable line; the first token on each line is the number of times that subroutine or line was executed. We can see here that the setSize() function has not been exercised at all in this test.

9.2.2 Devel::Cover

Paul Johnson's Devel::Cover module (http://search.cpan.org/dist/Devel-Cover/) is a more modern module with many more options than Devel::Coverage, but is still, according to its documentation, in its infancy.

Devel::Cover comes with a program, cover, that generates a database. The range of options is too great to go into here, but you can generate a coverage report at the granularity of lines by running

% perl -d:Cover=-coverage,statement program arguments...

and then generating a readable report from the database created in the default directory cover_db by running the program cover that comes with Devel::Coverage:

% cover -report text

    Previous Table of Contents Next
    © 2000- NIV