如何在运行时加载Perl模块?

cos*_*son 9 installation perl module

我想使用HTML :: Template模块.但是,它没有安装在我用于开发CGI脚本的服务器上.

是否可以在运行时加载模块:我在本地Perl安装上找到了Template.pm文件,并将文件上传到我正在使用的服务器上.

#!/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;
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 11

这是我做的:

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

script.pl(除非你在运行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
Run Code Online (Sandbox Code Playgroud)

如果HTML :: Template是真正可选的,请阅读perldoc -f require.

另请参见如何保留自己的模块/库目录?有什么要求和使用之间的区别?perlfaq8.


Eth*_*her 9

这与Sinan的答案类似,但使用local :: lib:

将文件设置为:

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

在你的脚本中:

use strict;
use warnings;
use local::lib 'lib';
use HTML::Parser;
Run Code Online (Sandbox Code Playgroud)

local :: lib的优点是您可以将CPAN中的模块直接安装到您选择的目录中:

perl -MCPAN -Mlocal::lib=lib -e 'CPAN::install("HTML::Parser")'
Run Code Online (Sandbox Code Playgroud)