bliof
bliof

Reputation: 2987

perl how to access func when the module is imported on the fly

I have a module which looks like this:

package Test;
use strict;
use warnings;

sub hello {
    my $val = shift
    print "val = $val\n";
}

and in another module I insert this one like this:

my $module = 'Test'
eval "require $module";

How can I call the function hello in the second module /I mean like a function not like a method/.

Upvotes: 2

Views: 224

Answers (3)

Eugene Yarmash
Eugene Yarmash

Reputation: 149726

You can use a symbolic reference:

{
    no strict 'refs';   # disable strictures for the enclosing block
    &{ $module . '::hello' };
}

Alternatively, you can export the function to the calling package (see Exporter):

package Test;
use Exporter 'import';
our @EXPORT = qw(hello);

sub hello {
...
}

Then in your code:

my $module = 'Test'
eval "use $module";
hello("test");

Upvotes: 3

ysth
ysth

Reputation: 98388

Another way:

$module->can('hello')->('test');

Upvotes: 2

yko
yko

Reputation: 2710

You can use the same eval in this purposes:

my $module = 'Test'
eval "require $module";

eval $module . "::hello()";

Also you can access symbol table and get reference to code of required sub:

my $code = do { no strict 'refs'; \&{ $module . '::hello' } };
$code->();

But this doesn't looks so clean.

However, if you need method-like call on package name, you can use just:

$module->new();

This also can be useful

Upvotes: 1

Related Questions