Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 961
coson Avatar asked Feb 18 '10 23:02

coson


2 Answers

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.

like image 181
Sinan Ünür Avatar answered Oct 08 '22 03:10

Sinan Ünür


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")'
like image 24
Ether Avatar answered Oct 08 '22 03:10

Ether