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;
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.
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")'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With