我想知道如何做到这一点:
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,看起来它符合您的需求.