我正在开发一个小的 Perl 模块,由于某种原因,我让使用我的新模块的测试驱动程序脚本调用了我认为是私有的函数之一,并且它成功了。我很惊讶,所以我开始搜索谷歌,我真的找不到任何关于如何在 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!
所以我在模块的最后一个右大括号后加了一个分号,但输出还是一样的。我真正发现的唯一一件事就是将此行作为第一行添加到我的 private_function 中:
caller eq __PACKAGE__ or die;
但这似乎很hacky。我没有很多编写 Perl 模块的经验,所以也许我的模块设置不正确?perl 模块中是否可以有私有函数和变量?
谢谢你帮助我学习!