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

Gau*_*nia 5 oop perl class-variables

我想知道如何做到这一点:

package Something;
our $secret = "blah";

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

我什么时候去

print Something->get_secret();
Run Code Online (Sandbox Code Playgroud)

我想要它打印blah.现在在你告诉我使用之前$secret,我想确保如果派生类使用Something作为基础,我打电话给get_secret我应该让那个类'秘密.

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

Sin*_*nür 5

$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";
Run Code Online (Sandbox Code Playgroud)

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