如何使用与主脚本在同一文件中定义的 Moose 类? [英] How to use a Moose class defined in the same file as the main script?

查看:37
本文介绍了如何使用与主脚本在同一文件中定义的 Moose 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下脚本 p.pl 工作正常:

The following script p.pl works fine:

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

my $obj = P1->new(name => 'John');
say "The name is: ", $obj->name;

其中 P1 类在文件 P1.pm 中定义:

where the class P1 is defined in file P1.pm:

package P1;
use Moose;

has name => (is => 'rw', isa => 'Str');

1;

但是,当我尝试将 P1.pm 类移动到主脚本中时:

However, when I try to move the class P1.pm into the main script:

#! /usr/bin/env perl

use feature qw(say);
use strict;
use warnings;

my $obj = P1->new(name => 'John');
say "The name is: ", $obj->name;

package P1;
use Moose;

has name => (is => 'rw', isa => 'Str');

出现错误:

Can't locate object method "name" via package "P1" at ./p.pl line 8.

推荐答案

has 只是一个在运行时执行的常规函数​​调用,因此它在您的 之后才会运行说.

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

通常你会useMoose 类,而 use Class;BEGIN { require Class; 的缩写;... },这样通常情况下,像 has 这样的所有 Moose 函数都将在执行 useing 的脚本的编译期间执行.另见 "BEGIN, UNITCHECK,CHECK、INIT 和 END"在 perlmod 中.

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.

虽然我认为这不是最好的解决方案,但您可以将 package P1; 声明粘贴在 BEGIN { ... } 块中.或者,您可以将 package P1 放在主代码之前(最好放在它自己的块中,因此它有自己的范围).

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).

但是也有一些反对首先将类放在同一个文件中的说法,参见例如在 Perl 中,如何将多个类放入单个 .pm 文件.

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.

这篇关于如何使用与主脚本在同一文件中定义的 Moose 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆