New to creating modules

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I would like to learn to use Perl modules properly, instead of bodging
them together as at present.  I have tried to understand what I read
about modules, but there are some gaps (in particular, the concepts
"file", "module", and "package" seem to overlap in a way that confuses
me).  I would therefore appreciate answers to a few questions.

(1.)  Does a package automatically end at the end of a file?

(2.)  Can packages nest?

(3.)  I like to begin my Perl files with
   use strict
but if the next line is
   @EXPORT = ( foo );
I get an error message.  I can remove the
   use strict
and get code that works, but there must be a better answer.  What is it?

(4.)  I can export functions from a module to a program, but how should
I export a variable?  I have found three ways:
(a.)  Declare it before the 'use strict' line
(b.)  Use  'our'
(c.)  Don't export the variable, export a little function that returns
its value.
None of these seems ideal - so what is the recommended method?

Nick Wedd

Re: New to creating modules

Hi Nick,

On Tue, 14 Jun 2011 13:07:34 +0100

Quoted text here. Click to load it

The 'package' keyword affects the current package until the end of the
compilation unit.  A common idiom is this:

package My::Package;

use strict;
use warnings;


Packages must end in a truthy statement to be loadable by require or

For more information on 'package', read its documentation here:

Quoted text here. Click to load it

Yes, but beware: this following code won't likely work as you think:

package Package;

package SubPackage; # this is the package SubPackage, not
                    # Package::SubPackage

In order to create Package::SubPackage, you need to do this:

package Package::SubPackage;

Quoted text here. Click to load it

Try this:

use strict;
our @EXPORT = qw(foo);

Quoted text here. Click to load it

Exporting variables is pretty uncommon, but if you're going to export
one, you'll need to declare it in package scope; ie. with 'our'.

Quoted text here. Click to load it

You might want to take a look at ;
it could clear up some of your confusion!


Re: New to creating modules

Quoted text here. Click to load it

Wrong.  `package' is lexically scoped.

Quoted text here. Click to load it

Packages can nest as any other lexically scoped stuff

  {  package A;
     ...        # in A
     { package B;
       ...        # in B
     ...        # in A

Quoted text here. Click to load it

If compatibility with older version is required, I prefer

  @EXPORT = @EXPORT = qw(foo);
  use strict;


Site Timeline