coson
coson

Reputation: 8659

How can I load a Perl module at runtime?

I would like to use the HTML::Template module. However, it is not installed on the server I'm using to develop CGI scripts.

Is it possible to load a module at runtime: I found the Template.pm file on my local Perl installation and uploaded the file to the server I'm using.

#!/usr/bin/perl -w

use CGI qw(:standard :html4);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);

# use HTML::Template;

use Template;

# my $package = "HTML::Template";
# eval {
# (my $pkg = $package) =~ s|::|/|g; # require need a path
# require "$pkg.pm";
# import $package;
# };
# die $@ if( $@ );

# open the HTML template
my $template = HTML::Template->new(filename => 'test.tmpl');

# fill in some parameters in the template
$template->param(home => $ENV{HOME});
$template->param(path => $ENV{PATH});

# send the obligatory Content-Type
print "Content-Type: text/html\n\n";

# print the template
print $template->output;

Upvotes: 9

Views: 4654

Answers (5)

Ether
Ether

Reputation: 53996

I should have added this as an option, since I'm one of the maintainers of this module: App::FatPacker can be used to include a third-party module with your application when it ships, so it does not need to be installed separately in the deployment environment.

Upvotes: 1

volvox
volvox

Reputation: 3060

Yes it is. Look at Module::Runtime. I would install your HTML module though, even in a local install directory. It's probably less hassle.

Upvotes: 0

Ether
Ether

Reputation: 53996

This is similar to Sinan's answer, but uses local::lib:

Set up your files as:

cgi-bin/script.pl
cgi-bin/lib/HTML/Template.pm

And in your script:

use strict;
use warnings;
use local::lib 'lib';
use HTML::Parser;

The advantage of local::lib is you can install modules from CPAN directly into a directory of your choosing:

perl -MCPAN -Mlocal::lib=lib -e 'CPAN::install("HTML::Parser")'

Upvotes: 9

Sinan Ünür
Sinan Ünür

Reputation: 118156

Here is what I do:

     cgi-bin/script.pl
     cgi-bin/lib/HTML/Template.pm

In script.pl (unless you are running under mod_perl):

 use FindBin qw( $Bin );
 use File::Spec::Functions qw( catfile );
 use lib catfile $Bin, 'lib';
 use HTML::Template;

 # The rest of your script

If HTML::Template is truly optional, read perldoc -f require.

See also How do I keep my own module/library directory? and What's the difference between require and use? in perlfaq8.

Upvotes: 11

rjh
rjh

Reputation: 50324

HTML::Template and Template are different Perl modules. If you want to use HTML::Template, you will need to use HTML::Template; at the top of the script to import that package.

Ensure that you copied the HTML/Template.pm file from your local machine to the server, rather than Template.pm.

Upvotes: 4

Related Questions