【问题标题】:Accessing class variables using a variable with the class name in perl在 perl 中使用具有类名的变量访问类变量
【发布时间】:2011-08-18 08:07:21
【问题描述】:

我想知道我该怎么做:

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,但有更优雅的解决方案吗?

【问题讨论】:

    标签: perl oop class-variables


    【解决方案1】:

    $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,看起来很适合您的需求。

    【讨论】:

      【解决方案2】:

      您可以使用symbolic reference

      no strict 'refs';
      return ${"${class}::secret"};
      

      【讨论】:

      • 谢谢尤金,不幸的是我们的代码必须use strict。还有其他方法可以引用吗?
      • @Gaurav,你为什么不能为那一行关闭严格?
      • @cjm 是的,我可以将其关闭一行,但它与使用 eval 一样不优雅,并且占用了 2 个以上的 LoC。 :)
      • @Gaurav-Dadhania: no strict 'refs' 更清晰。一旦你看到了这个结构,你就永远不会把它误认为是其他任何东西。 eval 仅表示您必须手动解析更多 Perl。
      • 关闭 strict 'refs' 比字符串 eval 安全得多。 strict 是您用来避免错误的工具,如果您知道必须这样做,将其关闭几行并没有错。 strict 可以提供帮助,而不是妨碍您或限制语言的力量
      猜你喜欢
      • 2017-11-01
      • 2013-12-24
      • 2015-09-25
      • 2011-10-31
      • 1970-01-01
      • 2019-09-22
      • 2014-07-29
      • 2011-08-28
      相关资源
      最近更新 更多