使用perl中具有类名的变量访问类变量

前端之家收集整理的这篇文章主要介绍了使用perl中具有类名的变量访问类变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道如何做到这一点:

package Something;
our $secret = "blah";

sub get_secret {
    my ($class) = @_;
    return; # I want to return the secret variable here
}

我什么时候去

print Something->get_secret();

我希望它打印出来.现在在你告诉我只使用$secret之前,我想确保如果派生类使用Something作为基础,并且我调用get_secret我应该得到该类的秘密.

你如何使用$class引用包变量?我知道我可以使用eval但是有更优雅的解决方案吗?

解决方法

$secret是否可以在包中修改?如果没有,你可以摆脱变量,而只是让一个类方法返回值.想要拥有不同秘密的类将覆盖该方法,而不是更改密钥的值.例如.:

package Something;

use warnings; use strict;

use constant get_secret => 'blah';

package SomethingElse;

use warnings; use strict;

use base 'Something';

use constant get_secret => 'meh';

package SomethingOther;

use warnings; use strict;

use base 'Something';

package main;

use warnings; use strict;

print SomethingElse->get_secret,"\n";
print SomethingOther->get_secret,"\n";

否则,perltooc包含适用于各种场景的有用技术. perltooc指向Class::Data::Inheritable,看起来它符合您的需求.

猜你在找的Perl相关文章