http://www.perlmonks.org?node_id=329104


in reply to Confused about splitting program into multiple files.

Here is the simplest example I could boil down for you showing how to do exactly what you're asking:

First, name a file "Mypackage.pm"...

# Mypackage.pm use strict; use warnings; use base Exporter; our @EXPORT = qw/mysub/; sub mysub { print "It works!\n"; } 1;

That sets up your module. You may leave it in the same directory as your script, or you can set up a location where you keep all your modules, and follow the instructions in the Camel book on how to let Perl know where to look for it. But in its easiest form, you're just leaving it in the same directory as your script.

The use base qw/Exporter/; line brings in the necessary behind-the-scenes code to allow you to set up all the tokens (subs, vars, etc) that you wish to make available to your main script. The our @EXPORTER = qw/mysub/; is your opportunity to enumerate exactly which subs and vars you wish to export into global namespace.

All of that export stuff would be unnecessary if you were willing to just call your subs as "Mypackage::mysub()". But since you're exporting, you can now call them just as "mysub();".

Oh, and modules always have to return a true value, and that's why the last line of the module is 1;.

Now your main script can just look like this:

#!/usr/bin/perl # main script file. use strict; use warnings; use Mypackage; mytest();

And your output is going to be just what we expect: "It works!"

I realize that this uses "exporting" to work. But it does so in a way that is pretty invisible to the main script. And asking to export to global namespace without using conventional Exporter techniques is a bit like asking to change a tire without a jack and tire-iron. In this case, it's just "how it's done". And as my example illustrates, it's pretty painless. You don't even have to get grease on your hands.


Dave