开发者

Perl : constant & require

I have a config file (config.pl) with my constants :

#!/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/";
...

And I would like to use these constants in index.pl, so index.pl starts with :

#!/usr/bin/perl -w
use strict;
use CGI;
require "config.pl";

how to use URL, CGI... in index.pl ?

Thanks,

Bye


EDIT

I found a solution :

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;

End


What you want to do here is setup a Perl module that you can export from.

Place the following into '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);

And then to use it:

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

By setting @ISA to Exporter in the MyConfig package, you setup the package to inherit from Exporter. Exporter provides the import method which is implicitly called by the use MyConfig; line. The variable @EXPORT contains the list of names that Exporter should import by default. There are many other options available in Perl's documentation and in the documentation for Exporter


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

or

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


BEGIN { require "config.pl"; }

And you must return a true value at the end of the required source. Usually:

1; 

Although, on certain modules I have done:

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

as the last statement in the file. And print returns a true anytime it prints a single character.

See require.


Troubleshooting

  • It could be a directory issue. The .pl file must be in @INC or modified by a path to the file.

Try this:

perl -Mconfig.pl -e 1

If it fails, look at the error message. Actually, in any event, you should be getting more with strict and warnings than "Oops, it failed."


You can't use barewords when you use strict.

A bareword is a essentially a variable name, without a sigil ($,@,%,&,*).

I suggest taking a look at the Readonly module on CPAN for creating constants.

The use constant pragma has a bunch of arcane magic going on that can result in difficult to debug code, if you're not careful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜