Home > Net >  Import symbols from package defined in the same file
Import symbols from package defined in the same file

Time:03-01

I hoped I could do something like this:

p.pl :

package Common;
use strict;
use warnings;
use experimental qw(signatures);
use Exporter qw(import);
our @EXPORT = qw(NA);
sub NA() { "NA" }


package Main;
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures);
Common->import();
say "Main: ", NA();
my $client = Client->new();
$client->run();


package Client;
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures);
Common->import();
sub run($self) {
    say "Client: ", NA();
}
sub new( $class, %args ) { bless \%args, $class }

to share common symbols between two packages in the same file. However running this script gives:

$ perl p.pl
Main: NA
Undefined subroutine &Client::NA called at ./p.pl line 30.

What am I missing here?

CodePudding user response:

The problem is that you call

$client->run();

before

Common->import();

A simple way to inline modules:

BEGIN {
    package Common;
    use strict;
    use warnings;
    use experimental qw(signatures);
    use Exporter qw(import);
    our @EXPORT = qw(NA);
    sub NA() { "NA" }
    $INC{"Common.pm"} = 1;
}

Then you can use use Common; as normal.

It's not perfect. Hooking into @INC like App::FatPacker does provides the best results. But it will make your life easier.

  •  Tags:  
  • perl
  • Related