perl私有方法两种实现

perl不像其他语言有private声明私有方法,但有变通方法。

一、利用调用者是否是同一个类,来隐藏私有方法(参考http://stackoverflow.com/questions/451521/how-do-i-make-private-functions-in-a-perl-module)

$cat test_priv.pl
package My;
sub new {
        return bless { }, shift;
}
sub private_func {
        my ($s,%args) = @_;
        die "Error: Private method called"
                unless (caller)[0]->isa( ref($s) );
        warn "OK: Private method called by " . (caller)[0];
}
sub public_func {
        my ($s,%args) = @_;
        $s->private_func();
}
package main;
my $obj = My->new();
$obj->public_func();
$obj->private_func();
 
$perl test_priv.pl
OK: Private method called by My at test_priv.pl line 9.
Error: Private method called at test_priv.pl line 7.

生成对象只能通过公共方法才能访问私有方法。

二、利用文件作用域,perl只能继承类的方法的特性

$cat test_priv2.pl
package Test;
sub new {
        return bless { }, shift;
}
my $private_func = sub {
   my $self = shift;
   print "I am private func!\n";
};
sub public_func {
   my $self = shift;
   print "I am public func!\n";
   $self->$private_func();
}
my $obj = Test->new();
$obj->public_func;
 
$perl test_priv2.pl
I am public func!
I am private func!

类继承以后,也能通过public_func来访问匿名函数(private)


Post a Comment