Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

module

perl

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?

like image 900
mjn12 Avatar asked Apr 15 '10 19:04

mjn12


People also ask

How do you refer variable within a package?

Another approach, frequently used, is to use different naming conventions for variables of different scope. For example, I commonly use "g_" to indicate a global variable in a package, and "l_" for local variables.

How do I print a variable name in Perl?

To do this, you need to use the module PadWalker, which lets you inspect the lexical pads that store variables. Show activity on this post. "my" (lexical) variables' names are erased, so you can't get their names. Package variables' names are available via the symbol table entry ( *var ), as mentioned elsearticle.

Which function in Perl allows you to include a module file or a module?

A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );

What is package name in Perl?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.


2 Answers

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;
like image 105
friedo Avatar answered Oct 06 '22 19:10

friedo


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;
}
like image 44
Ether Avatar answered Oct 06 '22 18:10

Ether