出口商在这里不合适。你自己说过:你可以use MyPackage;
初始化MyStruct
s。您给出的示例,如果在没有 Class::Struct 便利的情况下编写,将如下所示:
package MyPackage;
use Exporter qw(import);
our @EXPORT = qw(function1 function2);
sub function1 { ... }
sub function2 { ... }
1;
package MyStruct;
sub new # Constructor
{
my $self = shift;
my %args = @_;
return bless(
{
'MyStruct::type' => $args{type},
'MyStruct::other' => $args{other},
},
$self,
);
}
sub type # Setter/getter for type
{
my ($self, $set) = shift;
return $set ? $self->{type} = $set
: $self->{type};
}
sub other # Setter/getter for other
{
... # So on and so forth
}
1;
不同之处在于 Class::Struct 采用“蓝图”并MyStruct
为您编写类。From perlobj
:一个类只是一个包。一个类提供了期望对对象进行操作的方法。
将两个包放在一个文件中(这是 Class::Struct 隐式执行的操作)非常令人困惑,因此您可以将它们分开。
我的包.pm:
package MyPackage;
use parent qw(Exporter);
our @EXPORT_OK = qw(function1 function2);
sub function1 { ... }
sub function2 { ... }
1;
我的结构.pm:
package MyStruct;
use Class::Struct;
struct(
MyStruct => {
'type' => '$',
'other' => '$'
}
);
1;
您的问题尚不清楚,但如果MyPackage::function1()
要对 MyStruct 对象中包含的数据进行操作,您应该MyPackage
完全废弃并将其作为 MyStruct 中的方法提供:
package MyStruct;
use Class::Struct;
struct(
MyStruct => {
'type' => '$',
'other' => '$'
}
);
sub function1
{
my $self = shift;
print "This is function1 in $self\n";
}
1;
最后,不要从 MyStruct 中导出任何内容,而是像对象一样使用它:
use MyStruct;
my $instance = MyStruct->new( type => 'foo' ); # Instantiating
$instance->other('bar'); # Setting
print $instance->type; # Getting