Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用perl中具有类名的变量访问类变量_Perl_Oop_Class Variables - Fatal编程技术网

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

使用perl中具有类名的变量访问类变量,perl,oop,class-variables,Perl,Oop,Class Variables,我想知道我该怎么做: package Something; our $secret = "blah"; sub get_secret { my ($class) = @_; return; # I want to return the secret variable here } 现在我走的时候 print Something->get_secret(); 我想把它打印出来。现在,在您告诉我只使用$secret之前,我想确保如果派生类使用某物作为基,并且我调用get_

我想知道我该怎么做:

package Something;
our $secret = "blah";

sub get_secret {
    my ($class) = @_;
    return; # I want to return the secret variable here
}
现在我走的时候

print Something->get_secret();
我想把它打印出来。现在,在您告诉我只使用
$secret
之前,我想确保如果派生类使用
某物
作为基,并且我调用
get_secret
我应该获得该类的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
指出它似乎适合您的需要。

谢谢Eugene,不幸的是,我们的代码必须
使用严格的
。还有其他方法可以引用它吗?@Gaurav,为什么你不能为这一行关闭strict?@cjm是的,我可以为一行关闭它,但是它和使用
eval
一样不优雅,并且占用了另外两个位置。:)@Gaurav Dadhania:
没有严格的“参考”
更清楚。一旦你看到这个构造,你就不会把它错当成别的东西
eval
只意味着必须手动解析更多的Perl。关闭
strict'refs'
比字符串eval安全得多
strict
是一种用于避免错误的工具,如果您知道必须这样做,那么将其关闭几行也没有什么错
strict
是为了帮助您,而不是妨碍您或限制语言的力量
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";