Frew Schmidt
Frew Schmidt

Reputation: 9544

Should I change my utilities.pl to a utilities.pm module?

In our product we have a big utilities file that we require (with do) at the beginning of a lot of our files. Is there a reason not to turn this into a module? For example, instead of doing this:

do '../dbi_utilities.pl';
our ($db,$user,$pw,$attr);
my $Data = DBI->connect($db,$user,$pw,$attr) or die "Could not connect to database: $DBI::errstr";

Couldn't I just do this?:

use AppUtil;
my $Data = AppUtil->connect();

Upvotes: 6

Views: 364

Answers (5)

brian d foy
brian d foy

Reputation: 132906

By making your code into a module with proper refactoring, you make it easy to test. I write about this in my "Scripts as Modules" article for The Perl Journal as well as "How a Script Becomes a Module" on Perlmonks.

Good luck,

Upvotes: 7

J.J.
J.J.

Reputation: 4872

You get all of the cool module stuff, encapsulation, module specific functions, and so on.

Notice though, by using use with your syntax. creating an object for the AppUtil namespace, and calling the connect subroutine. for your utilities.

Also you must have 1; at the end of your file.


Sticking with the other method means you don't have to change any code, you don't have to add 1 at the end.

All "do", "use", and "require" import, but scope code that is within them (except named subroutines cause they can't be hidden).

Upvotes: 1

Leon Timmermans
Leon Timmermans

Reputation: 30235

Making a module out of it will make it a lot more robust. Right now a lot of things informally depend on each other, but those dependencies aren't immediately obvious.

Also, it would enable you to import only part of the utilities.

Upvotes: 2

bmdhacks
bmdhacks

Reputation: 16441

With do(), you're loading and compiling the utilities.pl file each time, which may cause problems if you do() it more than once. Also, use is done at compile which will allow your program to fail sooner, or even be tested with perl -wc.

Lastly, keeping it in a package allows you to protect it's namespace, which can be helpful as your project grows.

I would advise strongly to turn your utilites.pl into a proper Perl package that is loaded with use.

Upvotes: 6

Tanktalus
Tanktalus

Reputation: 22294

The only reason not to do this is time.

That is, it'll take time to clean up your interface, as well as all calling apps to use the new interface.

What it'll cost you in time now will be more than made up when you start using proper tests ("make test" or "./Build test" or just "prove ...") and be able to check that your changes won't break anything before checking it in. So, by all means, convert. Just be aware that it's not a free gain.

Upvotes: 9

Related Questions