Perl:常量和要求

eou*_*uti 5 perl constants require include

我有一个配置文件(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/";
...
Run Code Online (Sandbox Code Playgroud)

我想在index.pl中使用这些常量,所以index.pl以:

#!/usr/bin/perl -w
use strict;
use CGI;
require "config.pl";
Run Code Online (Sandbox Code Playgroud)

如何在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;
Run Code Online (Sandbox Code Playgroud)

index.pl

BEGIN {
    require "config.pm";
}
print Config::URL;
Run Code Online (Sandbox Code Playgroud)

结束

Eri*_*rom 3

您在这里要做的是设置一个可以从中导出的 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);
Run Code Online (Sandbox Code Playgroud)

然后使用它:

use MyConfig;  # which means BEGIN {require 'MyConfig.pm'; MyConfig->import} 
Run Code Online (Sandbox Code Playgroud)

通过在包中设置@ISAExporterMyConfig可以将包设置为从 继承ExporterExporter提供import由行隐式调用的方法use MyConfig;。该变量@EXPORT包含默认情况下应导入的名称列表ExporterPerl 的文档和Exporter的文档中还有许多其他可用选项