Lazer
Lazer

Reputation: 94840

Where should I put code that is common to two Perl modules?

I am creating several Perl modules which will use the common utilities for opening and closing files.

For example,

mod1.pm

my $in, $out;

sub openf {
    my $fname = shift;
    open $in, "<",  $fname or die $!;
}

sub one {
    openf($path);
    ...
}

mod2.pm

my $in, $out;

sub openf {
    my $fname = shift;
    open $in, "<",  $fname or die $!;
}

sub two {
    openf($path);
    ...
}

Now, where should I put openf so that the code is not duplicated?

Upvotes: 2

Views: 579

Answers (1)

DVK
DVK

Reputation: 129403

I'd say go with the simplest solution.

Make a 3rd module, Common.pm or Helpers.pm or MyUtils.pm - store all the common boilerplate helper subroutines there.

You will then import it from both of the modules above as well as anywhere else.

A slightly different approach is - instead of simply use-ing Commmon.pm - to actually inherit all your modules from it. That way they can extend the common utils as needed in OO fashion.

We actually did that with a large project, sub-classing almost 100% of modules from either BaseClass.pm or BaseClassPlus.pm which was its subclass. Worked very well and was very conductive to well-maintainable code due to significantly less boilerplate. (I have a feeling we could have done a large part of the work with Moose but that was before I even knew Moose existed)

Upvotes: 10

Related Questions