简体   繁体   English

如何在Perl中将变量用作模块名称?

[英]How can I use a variable as a module name in Perl?

I know it is possible to use a variable as a variable name for package variables in Perl. 我知道可以在Perl中使用变量作为包变量的变量名。 I would like to use the contents of a variable as a module name. 我想使用变量的内容作为模块名称。 For instance: 例如:

package Foo;
our @names =("blah1", "blah2");
1;

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. 在另一个文件中,我希望能够将标量的内容设置为“foo”,然后通过该标量访问Foo的names数组。

my $packageName = "Foo";

Essentially I want to do something along the lines of: 基本上我想做的事情是:

@{$packageName}::names; #This obviously doesn't work.

I know I can use 我知道我可以使用

my $names = eval '$'. $packageName . "::names" 

But only if Foo::names is a scalar. 但只有当Foo::names是标量时。 Is there another way to do this without the eval statement? 没有eval语句,还有另一种方法吗?

To get at package variables in package $package , you can use symbolic references: 要获取包$package中的包变量,可以使用符号引用:

no strict 'refs';
my $package = 'Foo';

# grab @Foo::names
my @names = @{ $package . '::names' }

A better way, which avoids symbolic references, is to expose a method within Foo that will return the array. 避免符号引用的更好方法是在Foo中公开将返回数组的方法。 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;

Strict checking is preventing you from using a variable (or literal string) as part of a name, but this can be disabled locally: 严格检查会阻止您将变量(或文字字符串)用作名称的一部分,但可以在本地禁用它:

my @values;
{
    no strict 'refs';
    @values = @{"Mypackage"}::var;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM