在 perl 中使用带有类名的变量访问类变量
我想知道我将如何去做:
package Something;
our $secret = "blah";
sub get_secret {
my ($class) = @_;
return; # I want to return the secret variable here
}
现在当我去的时候
print Something->get_secret();
我希望它打印blah
。现在,在您告诉我只使用 $secret
之前,我想确保派生类是否使用 Something
作为基础,并且我调用 get_secret
> 我应该得到那个班级的秘密。
如何使用 $class
引用包变量?我知道我可以使用 eval
但有更优雅的解决方案吗?
I'm wondering how I would go about doing this:
package Something;
our $secret = "blah";
sub get_secret {
my ($class) = @_;
return; # I want to return the secret variable here
}
Now when I go
print Something->get_secret();
I want it to print blah
. Now before you tell me to just use $secret
, I want to make sure that if a derived class uses Something
as base, and I call get_secret
I should get that class' secret.
How do you reference the package variable using $class
? I know I can use eval
but is there more elegant solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$secret
应该可以在包内修改吗?如果没有,您可以删除该变量,而只让类方法返回该值。想要拥有不同秘密的类将重写该方法,而不是更改秘密的值。例如:否则,perltooc 包含适合各种场景的有用技术。
perltooc
指向 Class::Data::Inheritable 看起来它会满足您的需求。Is
$secret
supposed to be modifiable within the package? If not, you can get rid of the variable and instead just have a class method return the value. Classes that want to have a different secret would then override the method, instead of changing the value of the secret. E.g.:Otherwise, perltooc contains useful techniques to fit a variety of scenarios.
perltooc
points to Class::Data::Inheritable which looks like it would fit your needs.您可以使用符号引用:
You can use a symbolic reference: