我有一个带有常量的配置文件(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...?
谢谢,
再见
编辑
我找到了一个解决方案:
配置文件
#!/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;
索引.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}
通过设置
@ISA
至Exporter
在 MyConfig
包,您将包设置为从 Exporter
继承. Exporter
提供import
use MyConfig;
隐式调用的方法线。变量 @EXPORT
包含 Exporter
的名称列表应该默认导入。 Perl 的文档和 Exporter 的文档中还有许多其他选项。
关于Perl : constant & require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5964594/