我正在开发一个 Perl 模块,但出于某种原因,我的测试驱动程序调用了其中一个我认为应该是私有的函数,并且执行成功。我很惊讶,于是开始在 Google 上搜索,但实际上找不到有关如何在 Perl 模块中创建私有函数的文档。
我看到有人建议在“私有”函数的闭括号后面加上分号,像这样:
sub my_private_function {
...
};
我尝试过这样做,但是我的驱动脚本仍然可以访问我想要私有化的函数。
我会编写一个更简短的例子,但是这就是我要达到的效果:
模块TestPrivate.pm:
package TestPrivate;
require 5.004;
use strict;
use warnings;
use Carp;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
@ISA = qw(Exporter AutoLoader);
our @EXPORT_OK = qw( public_function );
our @EXPORT = qw( );
$VERSION = '0.01';
sub new {
my ( $class, %args ) = @_;
my $self = {};
bless( $self, $class );
$self->private_function("THIS SHOULD BE PRIVATE");
$self->{public_variable} = "This is public";
return $self;
}
sub public_function {
my $self = shift;
my $new_text = shift;
$self->{public_variable} = $new_text;
print "Public Variable: $self->{public_variable}\n";
print "Internal Variable: $self->{internal_variable}\n";
}
sub private_function {
my $self = shift;
my $new_text = shift;
$self->{internal_variable} = $new_text;
}
驱动程序:TestPrivateDriver.pl
#!/usr/bin/perl
use strict;
use TestPrivate 'public_function';
my $foo = new TestPrivate();
$foo->public_function("Changed public variable");
$foo->private_function("I changed your private variable");
$foo->public_function("Changed public variable again");
$foo->{internal_variable} = "Yep, I changed your private variable again!";
$foo->public_function("Changed public variable the last time");
驱动器输出:
Public Variable: Changed public variable
Internal Variable: THIS SHOULD BE PRIVATE
Public Variable: Changed public variable again
Internal Variable: I changed your private variable
Public Variable: Changed public variable the last time
Internal Variable: Yep, I changed your private variable again!
因此,在模块的最后一个闭合大括号之后添加了一个分号,但输出结果仍然相同。我唯一真正发现的是在私有函数的第一行添加这一行:
caller eq __PACKAGE__ or die;
但这似乎相当hacky。我没有很多编写Perl模块的经验,所以也许我正在错误地设置我的模块?在Perl模块中是否可能有私有函数和变量?
谢谢帮助我学习!