我有一个配置文件(config.pl)与我的常量:
#!/usr/bin/perl use strict; use warnings; use Net::Domain qw(hostname hostfqdn hostdomain domainname); use constant URL => "http://".domainname()."/"; use constant CGIBIN => URL."cgi-bin/"; use constant CSS => URL."html/css/"; use constant RESSOURCES => URL."html/ressources/"; ...
我想在index.pl中使用这些常量,所以index.pl以:
#!/usr/bin/perl -w use strict; use CGI; require "config.pl";
如何在index.pl中使用URL,CGI …
谢谢,
再见
编辑
我找到了解决方案:
config.pm
#!/usr/bin/perl package Config; use strict; use warnings; use Net::Domain qw(hostname hostfqdn hostdomain domainname); use constant URL => "http://".domainname()."/"; use constant CGIBIN => URL."cgi-bin/"; 1;
index.pl
BEGIN { require "config.pm"; } print Config::URL;
结束
解决方法
你想在这里做的是设置一个可以从中导出的Perl模块.
将以下内容放入’MyConfig.pm’:
#!/usr/bin/perl package MyConfig; use strict; use warnings; use Net::Domain qw(hostname hostfqdn hostdomain domainname); use constant URL => "http://".domainname()."/"; use constant CGIBIN => URL."cgi-bin/"; use constant CSS => URL."html/css/"; use constant RESSOURCES => URL."html/ressources/"; require Exporter; our @ISA = 'Exporter'; our @EXPORT = qw(hostname hostfqdn hostdomain domainname URL CGIBIN CSS RESSOURCES);
然后使用它:
use MyConfig; # which means BEGIN {require 'MyConfig.pm'; MyConfig->import}
通过在MyConfig包中将@ISA设置为Exporter,可以将包设置为从Exporter继承. Exporter提供了使用MyConfig隐式调用的导入方法;线.变量@EXPORT包含Exporter默认导入的名称列表. Perl的文档和Exporter的文档中还有许多其他选项