krisraman has asked for the wisdom of the Perl Monks concerning the following question:

Monks How do I export a method from a package ?Also how do I do that for constants like the following use constant SUCCESS => 1; Can any one send me an example and explain it, if possible?
  • Comment on How do I export methods and constants from a package module?

Replies are listed 'Best First'.
Re: How do I export methods and constants from a package module?
by ehdonhon (Curate) on Apr 17, 2002 at 22:13 UTC

    The module you want to look at is Exporter. In general, if you create your modules using 'h2xs -X', all of this will be set up for you. You can export constants just like functions (because really, thats all they are)

    require Exporter; our @ISA = qw(Exporter); # Items to export into callers namespace by default. Note: do not expo +rt # names by default without a very good reason. Use EXPORT_OK instead. # Do not simply export all your public functions/methods/constants. # This allows declaration use My::Module ':all'; # If you do not need this, moving things directly into @EXPORT or @EXP +ORT_OK # will save memory. our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( );
      Yikes! What's with the require?
      use base 'Exporter'; our @EXPORT = qw[ functionA $variableB %mutantX ];
      You can forcibly export things with @EXPORT, or optionally with @EXPORT_OK. Then, when you import you have to ask for them, which is really the nice way to do it.
      package Foo; use Bar qw[ functionA ]; functionA($something);
      Simple enough, no?

        Yes, There is more than one way to do it. The code I posted was the standard output from h2xs. IMO, using h2xs is the most convenient way for a beginner to get things right.

Re: How do I export methods and constants from a package module?
by TheHobbit (Pilgrim) on Apr 17, 2002 at 22:30 UTC

    As someone told you, you must use Exporter. As far as constants are concerned, remember that constants are realy subs...

    Cheers
    Leo TheHobbit
    GED/CS d? s-:++ a+ C++ UL+++ P+++>+++++ E+ W++ N+ o K? !w O? M V PS+++
    PE-- Y+ PPG+ t++ 5? X-- R+ tv+ b+++ DI? D G++ e*(++++) h r++ y+++(*)