http://www.perlmonks.org?node_id=1073068

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

(disclaimer: I know that putting packages in the same file as 'main' is discouraged, but in this case I need to have it all in one file for distribution)
When a package is in a separate file, I know I can export various namespace elements by using:
require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(name1 name2 name3 ...);
Then when I include that package using 'use mypackage;', the namespace elements are available to my main routine.

Now in my case, the packages lie within the same file as my main routine (I surround each package with a 'BEGIN { }' block) so I don't need to (and can't) use 'use' to include the package and its exported namespace elements.

So, is there some way that I can 'import' the exported symbols when the package where they are exported is in the same file as main?

Replies are listed 'Best First'.
Re: Exporting namespace elements when package is in same file as main
by BrowserUk (Patriarch) on Feb 02, 2014 at 17:41 UTC

    Package::Name->import; # or Package::Name->import( ... );

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thanks! Works perfectly!
Re: Exporting namespace elements when package is in same file as main (BEGIN)
by tye (Sage) on Feb 02, 2014 at 19:57 UTC
    BEGIN { package Whatever; $INC{'Whatever.pm'} = __FILE__; use Exporter 'import'; @EXPORT_OK = qw< ... >; ... } package main; use Whatever qw< ... >; ...

    - tye        

Re: Exporting namespace elements when package is in same file as main
by tobyink (Canon) on Feb 02, 2014 at 21:48 UTC

    Just pimping Exporter::Shiny as it takes away some of the hassle...

    use strict; use warnings; BEGIN { package MyUtils; use Exporter::Shiny qw( answer ); sub answer { return 42; } } use MyUtils { prefix => 'my_' }, qw( answer ); print my_answer(), "\n";
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name