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;
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.
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?
To get at package variables in package
$package, you can use symbolic references:A better way, which avoids symbolic references, is to expose a method within
Foothat will return the array. This works because the method invocation operator (->) can take a string as the invocant.