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

时间:2022-04-01 20:26:34

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:

我知道可以在Perl中使用变量作为包变量的变量名。我想使用变量的内容作为模块名称。例如:

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. Is there another way to do this without the eval statement?

但只有当Foo :: names是标量时。如果没有eval语句,还有另一种方法吗?

2 个解决方案

#1


14  

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. This works because the method invocation operator (->) can take a string as the invocant.

避免符号引用的更好方法是在Foo中公开将返回数组的方法。这是因为方法调用操作符( - >)可以将字符串作为调用者。

package Foo;

our @names = ( ... );
sub get_names { 
    return @names;
}

package main;
use strict;

my $package = 'Foo';
my @names = $package->get_names;

#2


4  

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;
}

#1


14  

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. This works because the method invocation operator (->) can take a string as the invocant.

避免符号引用的更好方法是在Foo中公开将返回数组的方法。这是因为方法调用操作符( - >)可以将字符串作为调用者。

package Foo;

our @names = ( ... );
sub get_names { 
    return @names;
}

package main;
use strict;

my $package = 'Foo';
my @names = $package->get_names;

#2


4  

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;
}