Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi gurus. I need to know the syntax for substituting a variable for a package name. I can't seem to find it anywhere in my perl books. for example:
my $a = $test::countries;
$module = 'test'; my $a = ???
how would you replace the question marks? thanks so much. michael

Replies are listed 'Best First'.
Re: variable substition for packages
by jdporter (Paladin) on Jan 16, 2003 at 21:48 UTC
    Like this:
    $a = ${ $module . '::countries' };
    But note that you'll need to turn off strict references for this to work. That should tell you that it's probably a bad idea, right?

    But if you're doing object-oriented programming, you can use package names as "objects", like so:
    $a = $module->countries;
    and you can defined sub test::countries to return the contents of that variable.

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

Re: variable substition for packages
by tall_man (Parson) on Jan 16, 2003 at 21:25 UTC
    How about an eval?
    my $a = eval "\$${module}::countries";
    (By the way, are you sure you want to do this? There may be better ways to do what you need than symbolic expansions that refer to global variables.)

    Update:For example, Avoid Symbolic References talks about how you can often use a hash instead.