Perl : constant & require

标签 perl include constants require

我有一个带有常量的配置文件(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} 

通过设置 @ISAExporterMyConfig包,您将包设置为从 Exporter 继承. Exporter提供import use MyConfig; 隐式调用的方法线。变量 @EXPORT包含 Exporter 的名称列表应该默认导入。 Perl 的文档和 Exporter 的文档中还有许多其他选项。

关于Perl : constant & require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5964594/

相关文章:

字符串的 C char 到数组

c++ - 将整数引用值转换为 (const char*) 有什么影响,在 C++ 中转换为 char* 和转换为 const char* 有什么区别?

ruby - 通过继承的 Rspec 常量

perl - 哪些 Perl 模块适合数据处理?

perl - 如何在 Devel::Cover 的报告中列出未发现的 pm/pl 文件

c - 如果从标准输入读取,刷新标准输出似乎没有效果

c++ - 库依赖 C++ 项目

compiler-errors - 前向声明在MQL中无法按预期工作

xml - 如何在perl中获取xml元素的第一个和最后一个子元素

c++ - 将 Visual C++ 控制台输出写入或复制到文本文件