代码之家  ›  专栏  ›  技术社区  ›  Håkon Hægland

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

  •  0
  • Håkon Hægland  · 技术社区  · 4 年前

    我希望我能做这样的事:

    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.
    

    我在这里错过了什么?

    0 回复  |  直到 4 年前
        1
  •  3
  •   ikegami Gilles Quénot    4 年前

    问题是你打电话

    $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; 正常情况下。

    这并不完美。钩住 @INC 像App::FatPacker提供了最好的结果。但这会让你的生活更轻松。