从同一文件中定义的包中导入符号

Import symbols from package defined in the same file

我希望我能做这样的事情:

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 }

在同一文件中的两个包之间共享公共符号。但是 运行 这个脚本给出了:

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

我在这里错过了什么?

问题是你打电话

$client->run();

之前

Common->import();

内联模块的简单方法:

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;
}

那你就可以正常使用use Common;了。

它并不完美。像 App::FatPacker 一样连接到 @INC 确实提供了最好的结果。但它会让你的生活更轻松。