Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Confused about splitting program into multiple files.

by davido (Cardinal)
on Feb 15, 2004 at 06:43 UTC ( #329104=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://329104]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2021-10-26 08:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (90 votes). Check out past polls.

    Notices?