如何在Perl中使用变量作为模块名称? [英] How can I use a variable as a module name in Perl?
问题描述
我知道可以在Perl中将变量用作包变量的变量名.我想将变量的内容用作模块名称.例如:
I know it is possible to use a variable as a variable name for package variables in Perl. I would like to use the contents of a variable as a module name. For instance:
package Foo;
our @names =("blah1", "blah2");
1;
在另一个文件中,我希望能够将标量的内容设置为"foo",然后通过该标量访问Foo
中的名称数组.
And in another file I want to be able be able to set the contents of a scalar to "foo" and then access the names array in Foo
through that scalar.
my $packageName = "Foo";
基本上,我想按照以下方式做某事:
Essentially I want to do something along the lines of:
@{$packageName}::names; #This obviously doesn't work.
我知道我可以使用
my $names = eval '$'. $packageName . "::names"
但仅当Foo::names
是标量时.如果没有eval
语句,还有另一种方法吗?
But only if Foo::names
is a scalar. Is there another way to do this without the eval
statement?
推荐答案
要获取包$package
中的包变量,可以使用符号引用:
To get at package variables in package $package
, you can use symbolic references:
no strict 'refs';
my $package = 'Foo';
# grab @Foo::names
my @names = @{ $package . '::names' }
避免符号引用的更好方法是在Foo
中公开一个将返回数组的方法.之所以可行,是因为方法调用运算符(->
)可以将字符串作为调用者.
A better way, which avoids symbolic references, is to expose a method within Foo
that will return the array. This works because the method invocation operator (->
) can take a string as the invocant.
package Foo;
our @names = ( ... );
sub get_names {
return @names;
}
package main;
use strict;
my $package = 'Foo';
my @names = $package->get_names;
这篇关于如何在Perl中使用变量作为模块名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!