Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a module at runtime in Perl?

Tags:

module

perl

Is it possible to load a module at runtime in Perl? I tried the following, but it didn't work. I wrote the following somewhere in the program:

require some_module;
import some_module ("some_func");
some_func;
like image 433
petersohn Avatar asked May 18 '10 07:05

petersohn


People also ask

How do I call a Perl module function?

A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" ); Notice that we didn't have to fully qualify the package's function names. The use function will export a list of symbols from a module given a few added statements inside a module.

How do I install Perl modules in CPAN?

To install Perl modules using CPAN, you need to use the cpan command-line utility. You can either run cpan with arguments from the command-line interface, for example, to install a module (e.g Geo::IP) use the -i flag as shown.


2 Answers

Foo.pm

package Foo;

use strict;
use warnings;

use Exporter qw(import);
our @EXPORT = qw(bar);

sub bar { print "bar(@_)\n" }

1;

script.pl

use strict;
use warnings;

require Foo;
Foo->import('bar');
bar(1, 22, 333);
like image 71
FMc Avatar answered Oct 08 '22 19:10

FMc


The easiest way is probably to use a module like Module::Load:

use Module::Load;
load Data::Dumper;
like image 28
jkramer Avatar answered Oct 08 '22 20:10

jkramer