1

For whatever reason my coworkers (and probably myself in the past) have imported modules that we don't use to our projects. It's so bad that modules that don't even exist are being imported.

In Perl, you can say something like:

use Socket;
gethostname("DERP");

It's very hard to tell from that function that it was tied to the socket module.

Is there any program that exists or some functionality of Perl that I'm not aware of that can tell you if you've got bloat imported into your script?

FredMan
  • 861
  • 7
  • 19
  • 3
    For Python, this is answered in https://stackoverflow.com/questions/2540202/how-can-i-check-for-unused-import-in-many-python-files – Erik Cederstrand Oct 24 '17 at 13:51
  • Remove the import and run the test suite. You have one, right? – simbabque Oct 24 '17 at 14:04
  • 3
    The answer to this question is very different in Perl and in Python – the two are completely separate languages. Please clarify which of these two languages you want an answer for, and [edit] the tags accordingly. If necessary, ask a second question for another language. – amon Oct 24 '17 at 14:05
  • @amon done, that was very confusing. – Josep Valls Oct 25 '17 at 16:34

2 Answers2

4

That's why I always explicitly lists imports. e.g. use Socket qw( gethostname ); or use Foo qw( ); (The latter imports nothing rather than defaults.)

One approach would be to go file by file and add these import lists, then stop loading module with an empty import list for which no mention of its package name exists in the file.

ikegami
  • 367,544
  • 15
  • 269
  • 518
3

Use a profiler to see what modules ARE in use. From that find out which are not. Works for me:

  • Install the Devel::DProf module if you havent (cpanm Devel::DProf or if ubuntu: apt install libdevel-dprof-perl). Newer profilers also exists, i.e. Devel::NYTProf
  • Change #!/use/bin/perl to #!/use/bin/perl -d:DProf in your program and then run it. This will make a tmon.out file in your current dir
  • Run dprofpp -aO9999 to analyze tmon.out. This outputs all executed subs including the module name on each line.

Note: if a sub is called conditionally (inside an if-block for instance) the profiler will not list it if the condition is always false. It helps to have a test suit with full code coverage and run that in profiling mode.

Kjetil S.
  • 3,468
  • 20
  • 22
  • 2
    Changing the shebang is probably not a good idea (except when the program is not executed directly). Simply invoking `perl -d:DProf foo.pl` or setting the env var `PERL5OPT="$PERL5OPT -d:DProf"` are less intrusive solutions. – amon Oct 24 '17 at 16:22
  • 1
    DProf is deprecated. Please use NYTProf! – ikegami Oct 24 '17 at 19:56