I am building my first ever Perl module, and I am wondering what the best practice is of loading modules in your own module. I did read this answer, but it seems to talk about single file projects.
I started out by simply loading all modules I'd ever need in the project in the main file (let's call it MyModule.pm
), like so:
use Config::IniFiles;
use File::Spec qw(catdir catfile curdir);
use File::Path qw(remove_tree);
use File::Basename qw(fileparse dirname);
use Cwd qw(abs_path);
use XML::Twig;
use Getopt::Long;
But then I realised that not all modules (or subroutines/methods) are always necessary. For instance, it is possible that File::Path
is only required in a single method of the module, which has its own file (e.g. MyMethod.pm
). Would I then not use
File::Path in MyModule.pm
, but only in MyMethod.pm
Furthermore, should this be extended to specific use
'ing of subroutines as well? For instance, let's say I need to use catdir
in MyModule.pm and MyMethod.pm, but catfile in AnotherMethod.pm, would I split that up as well? I assume that Perl will just ignore a subroutine if it's already been imported but I am asking about the common practice. Would I do this?
# MyModule.pm
use File::Spec qw(catdir);
...
# MyMethod.pm
use File::Spec qw(catdir);
...
# AnotherMethod.pm
use File::Spec qw(catfile);
...
Or rather
# MyModule.pm
use File::Spec qw(catdir catfile);
...
# MyMethod.pm
use File::Spec qw(catdir catfile);
...
# AnotherMethod.pm
use File::Spec qw(catdir catfile);
...
Or even simply
# MyModule.pm
use File::Spec qw(catdir catfile);
...
To me it seems nice to split them up, as in the first example. That way, you immediately see what the dependencies for each file are. But I am wondering what the typical 'Perl style' for this is, or if there are up/downsides of any of these examples.