19
votes

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?

2
What do you mean by "access Foo"?Ether
Edited the question. I want to be able to access the package variable "@names" within foomjn12

2 Answers

18
votes

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

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;
4
votes

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