How to use a Moose class defined in the same file as the main script?

后端 未结 2 1930
醉梦人生
醉梦人生 2021-01-13 16:16

The following script p.pl works fine:

use feature qw(say);
use strict;
use warnings;
use lib \'.\';
use P1;

my $obj = P1->new(name => \'J         


        
2条回答
  •  逝去的感伤
    2021-01-13 16:35

    You are trying to use the attribute before executing the call to has that creates it.

    A relatively simple method to inline module follows:

    use feature qw(say);
    use strict;
    use warnings;
    
    use FindBin qw( $RealBin );
    use lib $RealBin;
    
    BEGIN {
       package P1;
       use Moose;
    
       has name => (is => 'rw', isa => 'Str');
    
       $INC{"P1.pm"} = 1;
    }
    
    use P1;
    
    my $obj = P1->new(name => 'John');
    say "The name is: ", $obj->name;
    

    Keep in mind it's still not quite equivalent. For example, the module is now in scope of the three pragmas in your script. Maybe you should use App::FatPacker or similar instead.

提交回复
热议问题