[Brisbane-pm] Messing with Modules

Jacinta Richardson jarich at perltraining.com.au
Fri Mar 16 16:29:37 PDT 2007


Martin Jacobs wrote:

> use input::Simple_Billycan_2_Stage;
> 
> The reason that it is not at the top, after #!/usr/local/bin/perl , is 
> that PERRMOSS will not know which module to call until line 369. 

This isn't going to make a difference.  When Perl first reads your files, it 
handles all the "use X" lines first, no matter where they appear in your file. 
If you really need to load these on a conditional basis then you're going to 
have to use require:

if( some_condition ) {
	eval "require 'input::Simple_Billycan_2_Stage.pm'";
	if($@) {
		print "Oops";
	}
}

or if you know that it'll definitely be there, and permissions will be good etc:

if( some_condition ) {
	require "input::Simple_Billycan_2_Stage.pm";
}

(above code untested, some tweaks may be necessary).  This is less than an ideal 
process though, so if you can deal with loading all of them and then just using 
the ones you need, that might be a better option.

> Simple_Billycan_2_Stage.pm includes the following (this is not the final 
> product, by the way);
> 
> package Simple_Billycan_2_Stage;
> require Exporter;
> our @ISA = qw(Exporter);
> our @Export = qw(camel);
> our @Export_OK = qw(weight);
> our $version = 1.00;
> 
> sub camel {print "One-hump dromedary\n"}
> 
> $weight = 1024;
> 
> 1;

Capitalisation matters in Perl.  I suggest you re-read perldoc Exporter or 
Chapters 12 and 13 in our Programming Perl course notese, or whichever chapters 
it is in the Programming Perl book.  Any of these sources should help you spot 
your error up there.

I recommend that you don't export things by default and instead allow the user 
to ask for them.  More on this below.

> Simple_Billycan_2_Stage::camel ();

When you are "using" this code you're writing:

	use input::Simple_Billycan_2_Stage;

This means that you're only going to have the default things exported.  "camel" 
is not exported by default.  So you'll need to write:

	use input::Simple_Billycan_2_Stage qw(camel);
	
	# this now works
	camel();

Exporting things by default (as you're doing with weight) is a bad idea because 
it can result in clashes between other modules (each exporting the same named 
symbol).  Further, it makes it very difficult for a maintainer to immediately 
recognise where a particular symbol comes from.  Exporting on request (as we do 
with camel) means that when the maintainer searches for the symbol throughout 
the code they will eventually find it next to its exporting module name.

> What I am looking for is a way to reference a block of code that is 
> outside the main program. I understand that modules are the way to go, 
> but if there is a simpler way to do it, I would be glad to know about it.

Modules are definitely the way to go.  :)  They'll make more sense as you use 
them more.

All the best,

	Jacinta


More information about the Brisbane-pm mailing list