Search code examples
perlmoduleperl-module

Perl module dependency organization and include order


I am aware of cyclic module dependency in perl and the fact that it is very bad idea e.g.:

package ModuleA;
use ModuleB;

package ModuleB;
use ModuleA;

I want to ask if following model is safe and if it follows some best practicing rules:

package main;
use ModuleA;
use ModuleB;

package ModuleA;
use ModuleB;
use ModuleC;

package ModuleB;
use ModuleC;

Also I would like to ask if the order of use-ing modules have any impact? e.g. if

package main;
use ModuleA;
use ModuleB;

is the same as

package main;
use ModuleB;
use ModuleA;

and if

package ModuleA;
use ModuleB;
use ModuleC;

is the same as

package ModuleA;
use ModuleC;
use ModuleB;

etc.

EDIT: Note to say that ModuleA loads ModuleC explicitly (and do not rely on ModuleB that it will load ModuleC) because ModuleA uses functions from ModuleC. Is this good design approach?


Solution

  • The best practice is easy: Each file, program or module, should specify all its dependencies. That's it. E.g., if a script needs modules A and B, and module A needs module B, don't count on module B already loaded by the script - what if some other script needs module A without needing B?

    Good Exporter based modules should use @EXPORT_OK and you should explicitly list the imported subroutines in the use-clause. It helps to prevent name clashes.

    For normal modules that only export subroutines, order shouldn't matter. In other cases, it might, though: consider

    use warnings_;
    use diagnostics;
    

    versus

    use diagnostics;
    use warnings_;