使用perl中具有类名的变量访问类变量
发布时间:2020-12-16 06:28:51 所属栏目:大数据 来源:网络整理
导读:我想知道如何做到这一点: package Something;our $secret = "blah";sub get_secret { my ($class) = @_; return; # I want to return the secret variable here} 我什么时候去 print Something-get_secret(); 我希望它打印出来.现在在你告诉我只使用$secret
我想知道如何做到这一点:
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,看起来它符合您的需求. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |