Perl:常数和要求

时间:2011-05-11 12:55:32

标签: 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 ... 谢谢,
再见


修改
我找到了解决方案:
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;

结束

4 个答案:

答案 0 :(得分: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);

然后使用它:

use MyConfig;  # which means BEGIN {require 'MyConfig.pm'; MyConfig->import} 

通过在@ISA包中将Exporter设置为MyConfig,您可以将包设置为从Exporter继承。 Exporter提供了由import行隐式调用的use MyConfig;方法。变量@EXPORT包含Exporter默认情况下应导入的名称列表。 Perl的文档和Exporter

的文档中提供了许多其他选项

答案 1 :(得分:2)

BEGIN {
    require "config.pl";
}
print URL;

require "config.pl";
print URL();

答案 2 :(得分:2)

BEGIN { require "config.pl"; }

您必须在所需来源的末尾返回一个真值。通常:

1; 

虽然,我已经完成了某些模块:

print "My::Mod included...\n";

作为文件中的最后一个语句。 print只要打印一个字符就会返回true。

请参阅require


疑难解答

  • 这可能是目录问题。 .pl文件必须位于@INC中,或者由文件路径修改。

试试这个:

perl -Mconfig.pl -e 1

如果失败,请查看错误消息。实际上,无论如何,你应该得到更多的严格和警告,而不是“哎呀,它失败了。”

答案 3 :(得分:0)

use strict时,您无法使用裸字。

裸字本质上是一个变量名,没有sigil($,@,%,&,*)。

我建议您查看CPAN上的Readonly模块以创建常量。

如果你不小心的话,use constant pragma会有一堆神秘的魔法,这会导致代码难以调试。