Reputation: 2987
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
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
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