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

后端 未结 2 1944
醉梦人生
醉梦人生 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:53

    has is just a regular function call that gets executed at runtime, so it won't get run until after your say.

    Normally you'd use a Moose class, and use Class; is just short for BEGIN { require Class; ... }, so that normally, all the Moose functions like has will have been executed during the compile time of the script that is doing the useing. See also "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod.

    Although I don't think it's the nicest solution, you could stick your package P1; declaration in a BEGIN { ... } block. Or, you could put package P1 before the main code (in its own block would be best, so it has its own scope).

    But there's also something to be said against putting the class in the same file in the first place, see e.g. the answers at In Perl, how do I put multiple class in a single .pm file.

提交回复
热议问题