> -----Original Message-----
> From: Bruce Ferrell [mailto:[EMAIL PROTECTED]]
> Sent: Monday, November 19, 2001 11:41 AM
> To: [EMAIL PROTECTED]
> Subject: Use of packages 
> 
> 
> I came up with this question while I was reading Paul Dubois 
> book MySQL
> and PERL for the Web.  I'm not sure I'm clear on a concept, so I'm
> posting it here in pseudo perl hope of getting some clarity.
> 
> A package (module?) is created thusly:
> 
> #begin perl package
> package packagename;
> 
> sub sub1 {
>           perl code here
> }
> 
> sub sub2 {
>            more perl code
> }
> 1; #return true
> #end package
> 
> Now, I'm presenting two examples of how to use the package I just made
> in an actual perl script.  The first I know to be correct, 
> the second is
> the one I'm unclear on:
> 
> #begin example 1
> use packagename;
> 
> packagename::sub1();
> packagename::sub2();
> #end example 1
> 
> #begin example 2
> use packagename();
> sub1();
> sub2();
> #end example 2
> 
> No can someone explain to me what, if anything is incorrect about the
> second example?  What I'm looking for is how sub-routines are 
> used from
> a used module without the module name prefix.

The latter requires using the "Exporter" feature whereby a package can
place aliases to its functions, variables, etc. in the calling package's
namespace. To enable this, you need the following:

In the module, include the following:

   require Exporter;
   our @ISA = qw(Exporter);
   our @EXPORT = qw(sub1 sub2);

In the main program, do:

   use packagename;     # note no parens

The "use" statement will call packagename's import() method, which it
inherits from Exporter. This by default will create an alias in the calling
package for each symbol in @EXPORT().

Supplying parens on the use:

   use packagename ();

Will override this behavior and suppress the importing of symbols from
@EXPORT.

Note that using @EXPORT is somewhat frowned upon, since it causes packages
to "pollute" the namespace of the calling package. The more "polite" form
is to use @EXPORT_OK, which only imports symbols if they are explicitly
named in the use statement.

So you could say in the module:

   our @EXPORT = qw();              # export nothing by default
   our @EXPORT_OK = qw(sub1 sub2);  # but allow these to be exported

Then in the main program:

   use packagename qw(sub1 sub2);

See:

perldoc perlmod
perldoc Exporter
perldoc -f use



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to